http://poj.org/problem?id=1564
The problem uses DFS but to pay attention to the heavy, can not output duplicate answers
There are two kinds of de-weight methods in the code that are marked
The first if (a[i]!=a[i-1]) means that if the number A[i] is the same as the previous number, then there is no need to put that number in the same position of the record array. For example: 4 3 3 2 The composition and the second position of the 7,b array is 3, then the next 3 does not need to be placed in the second position of the record array. (may be placed in the back position) ...
#include <stdio.h>#include<string.h>#include<math.h>#include<stdlib.h>#include<vector>#include<algorithm>#defineN 110using namespacestd;intA[n], b[n];intT, N, F;intcmpConst void*a,Const void*b) { return*(int*) B-* (int*) A;}voidDFS (intKintJintsum) { inti; if(Sum = =t) {f=1; Qsort (b, J,sizeof(b[0]), CMP); printf ("%d", b[0]); for(i =1; I < J; i++) printf ("+%d", B[i]); printf ("\ n"); return ; } for(i = k; i < n; i++) { if(A[i]! = a[i-1] || i = =k) {B[j]=A[i]; DFS (i+1, J +1, Sum +A[i]); } /*if (sum + a[i] <= t) {b[j] = A[i]; DFS (i + 1, j + 1, sum + a[i]); while (a[i] = = a[i + 1] && i + 1 < n) i++;//de-weight}*/ }}intMain () {inti; while(SCANF ("%d%d", &t, &n), T +N) {f=0; for(i =0; I < n; i++) scanf ("%d", &A[i]); Qsort (A, N,sizeof(a[0]), CMP); printf ("Sums of%d:\n", T); DFS (0,0,0); if(f = =0) printf ("none\n"); } return 0;}
POJ 1564 Sum It up (dfs+ de-weight + sort)