從給定的N個正數中選取若干個數之和為M
#include <iostream> #include <list> using namespace std; void find_seq(int sum, int index, int * value, list<int> & seq) { if(sum <= 0 || index < 0) return; if(sum == value[index]) { printf("%d ", value[index]); for(list<int>::iterator iter = seq.begin(); iter != seq.end(); ++iter) { printf("%d ", *iter); } printf("\n"); } seq.push_back(value[index]); find_seq(sum-value[index], index-1, value, seq); //放value[index] seq.pop_back(); find_seq(sum, index-1, value, seq); //不放value[index] } int main() { int M; list<int> seq; int value[] = {2,9,5,7,4,11,10}; int N = sizeof(value)/sizeof(value[0]); for(int i = 0; i < N; ++i) { printf("%d ",value[i]); } printf("\n"); scanf("%d", &M); printf("可能的序列:\n"); find_seq(M, N-1, value, seq); return 0; }