/* Name: NYOJ--1058--部分和问题 Author: shen_渊 Date: 15/04/17 19:27 Description: 简单的DFS,以为马上过的,递归的i+1写错了,重复好多情况 */ #include<iostream> #include<cstring> using namespace std; void dfs(int,int); int n,k,flag; int arr[22]; int vis[22]; int main() { // freopen("in.txt","r",stdin); while(cin>>n>>k){ memset(vis,0,sizeof(vis)); memset(arr,0,sizeof(arr)); flag = 0; for(int i=0; i<n; ++i)cin>>arr[i]; dfs(0,0); if(!flag)cout<<"NO "; } return 0; } void dfs(int ct,int val){ if(val == k){ if(!flag){ flag = 1; cout<<"YES "; } for(int i=0; i<n; ++i) if(vis[i])cout<<arr[i]<<" "; cout<<endl; } for(int i=ct; i<n; ++i){//有多个选择,不同的选择项有选择与不选择 if(val+arr[i] <= k){ vis[i] = 1;//标记的作用是输出 dfs(i+1,val+arr[i]);// 错了好久ct+1会重复= = i+1一直向下搜索 例子中如果搜到 2 4 7 就不能搜 4 2 7 vis[i] = 0; } } }