POJ 1564 经典dfs

时间:2024-12-03 09:07:43

1、POJ 1564 Sum It Up

2、总结:

题意:在n个数里输出所有相加为t的情况。

#include<iostream>
#include<cstring>
#include<cmath>
#include<queue>
#include<algorithm>
#include<cstdio>
#define F(i,a,b) for (int i=a;i<=b;i++)
#define mes(a,b) memset(a,b,sizeof(a))
#define INF 0x3f3f3f3f
#define LL long long
using namespace std;
const int N=,MAX=; bool flag;
int t,n;
int num[],ans[]; void dfs(int cnt,int k,int sum)
{
if(sum==t){
flag=false;
F(i,,cnt-){
if(i==)printf("%d",ans[i]);
else printf("+%d",ans[i]);
}
printf("\n");
return ;
} //关键
F(i,k,n){
if(i==k||num[i]!=num[i-]&&sum+num[i]<=t){
ans[cnt]=num[i];
dfs(cnt+,i+,sum+num[i]);
}
}
} int main()
{
while(~scanf("%d%d",&t,&n),t&&n)
{
flag=true;
F(i,,n)scanf("%d",&num[i]);
printf("Sums of %d:\n",t);
dfs(,,);
if(flag)printf("NONE\n"); } return ;
}