部分和问题

来源:互联网 发布:论文投稿选择中教数据 编辑:程序博客网 时间:2024/05/28 23:11

题意:给定整数a1,a2,a3...an,判断是否可以从中选出若干数,使它们的和恰好为k.

解答:dfs

注意:只要存在一种方案,就是true!

#include<iostream>#include<cstdio>#include<cstring>using namespace std;const int MAXN = 110;int n,a[MAXN],k;bool dfs(int step,int t){    if(step == n+1)    {        return t == 0;    }    if(dfs(step+1,t-a[step])) return true;//!!!    if(dfs(step+1,t)) return true;//!!!    return false;}int main(){    while(~scanf("%d",&n))    {        for(int i = 1;i <= n;i++)            scanf("%d",&a[i]);        scanf("%d",&k);        if(dfs(1,k) == true)            puts("Yes");        else            puts("No");    }    return 0;}