hdu 1258 从n个数中找和为t的组合 (DFS)
题意:首先给你一个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 8 int a[20] ; 9 int save[20] ; 10 int n , t ; 11 bool flag ; 12 13 bool cmp(const int &x , const int &y) 14 { 15 return x > y ; 16 } 17 18 void dfs(int count , int L , int pos) 19 { 20 if (L > t) 21 return ; 22 if (L == t) 23 { 24 for(int j=0;j<count-1;j++) 25 { 26 printf("%d+",save[j]); 27 } 28 printf("%d\n",save[count-1]); 29 flag = 1 ; 30 return ; 31 } 32 for (int i = pos ; i < n ; i++) 33 { 34 save[count] = a[i] ; 35 dfs (count+1,L+a[i] , i+1) ; 36 while (a[i] == a[i+1]) 37 i++ ; 38 } 39 40 } 41 42 int main() 43 { 44 //freopen("in.txt","r",stdin) ; 45 46 while (scanf("%d %d" , &t , &n) != EOF) 47 { 48 if (t == 0 && n == 0) 49 break ; 50 int i ; 51 for (i = 0 ; i < n ; i++) 52 { 53 scanf("%d" , &a[i]) ; 54 } 55 sort(a,a+n,cmp) ; 56 flag = 0 ; 57 printf("Sums of %d:\n",t); 58 dfs(0,0,0) ; 59 if (flag == 0) 60 { 61 printf("NONE\n") ; 62 } 63 } 64 65 return 0 ; 66 67 }