D 遞歸
題目
知識點
遞歸大家應該都會吧
練習題
從1~n中選取任意多(大於0)個數字,輸出所有可能的選擇方案
輸入
一行一個整數
輸出
多行,每行一種方案
同一行內的數必須升序排列,相鄰兩個數用恰好1個空格隔開。
方案按照字典序由小到大輸出。
輸入樣例
3
輸出樣例
1
1 2
1 2 3
1 3
2
2 3
3
思路
遞歸
代碼
#include <iostream>
#include <algorithm>
typedef long long ll;
using namespace std;
const int ms = 24;
int n;
int num[ms];
inline void init_cin()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
}
void dfs(int x, int cur)
{
if (x > 0)
{
for (int i = 0; i < x; ++i)
{
printf("%d ", num[i]);
}
puts("");
}
for (int i = cur + 1; i <= n; ++i)
{
num[x] = i;
dfs(x + 1, i);
}
}
int main()
{
init_cin();
cin >> n;
dfs(0, 0);
return 0;
}