首页 > 其他 > 详细

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

时间:2020-05-28 11:29:12      阅读:39      评论:0      收藏:0      [点我收藏+]

#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;
}

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

原文:https://www.cnblogs.com/Joe2019/p/12979021.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!