(一)增量構造法
#include#include using namespace std; const int MAXN = 1000; int A[MAXN], n; void print_subset(int n, int *A, int cur) { for(int i = 0; i < cur; ++i) cout << A[i] << " "; cout << endl; int s = (cur ? A[cur-1]+1 : 0); //選取當前填到第cur個位置上的可以填的最小是數字! for(int i = s; i < n; ++i) { A[cur] = i; print_subset(n, A, cur+1); } } int main() { cin >> n; print_subset(n, A, 0); return 0; }
#include必須當“所有元素是否選擇”全部確定完畢後才是一個完整的子集。#include using namespace std; const int MAXN = 1000; int B[MAXN], n; void print_subset(int n, int *B, int cur) { if(cur == n) { for(int i = 0; i < cur; ++i) { if(B[i]) cout << i << " "; } cout << endl; return ; } B[cur] = 1; //選第cur個元素 print_subset(n, B, cur+1); B[cur] = 0; //不選第cur個元素 print_subset(n, B, cur+1); } int main() { cin >> n; print_subset(n, B, 0); return 0; }