题意:给定整数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;
}
本文介绍了一个使用深度优先搜索(DFS)算法来解决子集和问题的经典案例。该问题要求从一组整数中找出是否存在某些数的组合,使得这些数的总和等于给定的目标值k。通过递归调用DFS函数,程序尝试每一种可能的组合,直到找到解决方案或者确认没有解。
11万+

被折叠的 条评论
为什么被折叠?



