深度搜索---------部分和问题

#include<iostream>
#include<stack>
#define maxn 30
using namespace std;
stack<int>st;
int n,k,a[maxn];
bool dfs(int i,int sum)
{
    if(i==k) return sum==k;//加到最后一个
    if(dfs(i+1,sum)) return true;//不加a【i】
    if(dfs(i+1,sum+a[i]))
    {
        st.push(a[i]);
        return true;
    }
    return false;
}
int main()
{
    while(cin>>n>>k)
    {
        for(int i=0;i<n;i++)
            cin>>a[i];
        if(dfs(0,0))
        {
            cout<<"YES"<<endl;
            while(!st.empty())
            {
                cout<<st.top()<<" ";
                st.pop();
            }
            cout<<endl;
        }
        else cout<<"NO"<<endl;
    }
    return 0;
}

posted @ 2020-05-28 10:47  Joelin12  阅读(104)  评论(0)    收藏  举报