2019E1_D 递归

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_44024733/article/details/102752508

D 递归

题目

知识点

递归大家应该都会吧

练习题

从1~n中选取任意多(大于0)个数字,输出所有可能的选择方案

输入

一行一个整数 n ( 1 = < n < = 10 ) n(1=<n<=10)

输出

多行,每行一种方案

同一行内的数必须升序排列,相邻两个数用恰好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;
}

猜你喜欢

转载自blog.csdn.net/weixin_44024733/article/details/102752508