Linux下安裝並使用MySQL資料庫
阿新 • • 發佈:2020-12-30
遞迴實現指數型列舉
題目描述
從 1~n 這 n 個整數中隨機選取任意多個,輸出所有可能的選擇方案。
輸入格式
輸入一個整數n。
輸出格式
每行輸出一種方案。
同一行內的數必須升序排列,相鄰兩個數用恰好1個空格隔開。
對於沒有選任何數的方案,輸出空行。
本題有自定義校驗器(SPJ),各行(不同方案)之間的順序任意。
資料範圍
1≤n≤15
輸入樣例
3
輸出樣例
3
2
2 3
1
1 3
1 2
1 2 3
題目思路
用dfs遞迴的方式來進行遍歷,st[i]=1表示選擇這個數,st[i]=2表示不選這個數。
#include<cstdio> #include<iostream> #include<cstring> using namespace std; const int N = 16; int n,st[N]; void dfs(int u) { if(u > n) { for(int i=1;i<=n;i++) if(st[i] == 1) printf("%d ",i); puts(""); return ; } st[u] = 1;//選 dfs(u + 1); st[u] = 2;//不選 dfs(u + 1); } int main() { cin >> n; dfs(1); return 0; }