题意:首先给你一个t,然后是n,后面输入n个数,然后让你求的是n个数中和为t的序列总共有多少种,把他们按从左到右的顺序输出来。
Sample Input
4 6 4 3 2 2 1 1
5 3 2 1 1
400 12 50 50 50 50 50 50 25 25 25 25 25 25
0 0
Sample Output
Sums of 4:
4
3+1
2+2
2+1+1
Sums of 5:
NONE
Sums of 400:
50+50+50+50+50+50+25+25+25+25
50+50+50+50+50+25+25+25+25+25+25
1 # include <cstdio> 2 # include <cmath> 3 # include <iostream> 4 # include <cstring> 5 # include <algorithm> 6 using namespace std ; 7 int t,n,flag; 8 int num[14],save[14]; 9 10 bool cmp(int x , int y) 11 { 12 return x > y ; 13 } 14 15 void dfs(int i,int sum,int count){ 16 if(sum>t) 17 return ; 18 if(sum==t){ 19 for(int j=0;j<count-1;j++){ 20 printf("%d+",save[j]); 21 } 22 printf("%d\n",save[count-1]); 23 flag=1; 24 return; 25 } 26 int tag=-1; 27 for(int k=i;k<n;k++){ 28 if(num[k]!=tag){ 29 save[count]=num[k]; 30 sum+=num[k]; //每次的和 31 tag=num[k]; //保留当前的数,能避免重复 假如是 4 2 2 前一个2已经被排除 则不用考虑后一个2 32 dfs(k+1,sum,count+1); 33 sum-=num[k]; 34 } 35 } 36 } 37 38 int main(){ 39 // freopen("in.txt","r",stdin) ; 40 while(scanf("%d%d",&t,&n)!=EOF){ 41 if(n==0)break; 42 for(int i=0;i<n;i++){ 43 scanf("%d",&num[i]); 44 } 45 flag=0; 46 sort(num,num+n,cmp) ; 47 printf("Sums of %d:\n",t); 48 dfs(0,0,0); 49 if(!flag){ 50 printf("NONE\n"); 51 } 52 53 } 54 return 0; 55 }
时间: 2024-10-09 18:19:43