代码:
#include <bits/stdc++.h> using namespace std; const int maxn = 18; int n; int vis[maxn]; // 选 or 不选 int a[maxn]; int f(int x) { if (x == n) { for (int i = 1; i <= n; i++) { if (vis[i]) cout << a[i] << " "; } cout << endl; return 0; } else { vis[x + 1] = 1; f(x + 1); vis[x + 1] = 0; f(x + 1); } } int main() { cin >> n; for (int i = 1; i <= n; i++) { a[i] = i; } f(0); // 从0开始 }
或者f(1):
#include <bits/stdc++.h> using namespace std; const int maxn = 18; int n; int vis[maxn]; // 选 or 不选 int a[maxn]; int f(int x) { if (x > n)//f(1)开始,所以x > n 时结束 { for (int i = 1; i <= n; i++) { if (vis[i]) cout << a[i] << " "; } cout << endl; return 0; } else { vis[x] = 1;//选 f(x + 1); vis[x] = 0;//不选 f(x + 1); } } int main() { cin >> n; for (int i = 1; i <= n; i++) { a[i] = i; } f(1); // 从1开始 }