NYOJ 部分和问题(DFS)

版权声明:本文为博主原创文章,转载请注明出处: https://blog.csdn.net/SL_World/article/details/79699243

1
思路:经典DFS问题,对于NO可以设个标志。注意当和(cur)==k的时候,尾部一定要加上return;否则无法AC!

#include <iostream>
#include <cstring>
using namespace std;
int n,k;
int a[21];
bool vis[21],judge = true;
void dfs(int t,int cur){
    if(t>n||cur>k) return;
    if(cur==k){
            cout<<"YES"<<endl;
            for(int i=0;i<n;i++)
                if(vis[i]) cout<<a[i]<<" ";
            cout<<endl;
            judge = false;
            return;
    }   
    if(cur+a[t]<=k){
        vis[t] = true;
        dfs(t+1,cur+a[t]);
        vis[t] = false;
    }
    dfs(t+1,cur);
}
int main(){
    while(cin>>n>>k){
        memset(a,0,sizeof(a));
        memset(vis,false,sizeof(vis));
        for(int i=0;i<n;i++) 
            cin>>a[i];
        judge = true;
        dfs(0,0);
        if(judge) cout<<"NO"<<endl;
        }
    return 0;
}

运行结果:

YES
2 4 7
展开阅读全文

没有更多推荐了,返回首页