时间复杂度度 O(2^n)
#include<iostream> #include<cstring> #include<vector> #include<algorithm> using namespace std; const int maxn = 1000 + 10; const int inf = 0x7fffffff; vector<int>chose; int n; void calc(int x){ if (x == n + 1){ //问题边界 for (int i = 0; i < chose.size(); i++) printf("%d ",chose[i]); cout << endl; return; } //"不选x"的分支 calc(x + 1); //子问题 //"选x"的分支 chose.push_back(x); //记录x已被选择 calc(x + 1); //子问题 chose.pop_back(); //准备回溯到上一问题之前,还原现场 } int main() { cin >> n; calc(1); return 0; }
原文:https://www.cnblogs.com/looeyWei/p/10529427.html