鱼C论坛

 找回密码
 立即注册
查看: 979|回复: 2

[已解决]程序

[复制链接]
发表于 2023-11-21 19:55:16 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
描述
走楼梯时,后面的跨步要求大于前面的跨步,最大一次允许跨n级。任意走几步,有几种走法

输入
正整数n(n<10)
输出
多行,每行表示一种走法
样例输入
3
样例输出
1
12
123
13
2
23
3
C++
最佳答案
2023-11-21 20:42:08
#include <iostream>
#include <vector>
#include <string>
using namespace std;

void dfs(int n, int cur, string path) {
        //cout << n << " " << cur << " " << path << endl;
        if(cur == n) return;
    for (int i = cur + 1; i <= n; ++i) {
        path += (i+'0');
        cout << path << endl;
        dfs(n, i, path);
        path.erase(path.size()-1, 1);
        }
}

int main() {
    int n;
    cin >> n;
    dfs(n, 0, "");
    return 0;
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-11-21 19:55:25 | 显示全部楼层
#include <iostream>
#include <vector>
#include <string>
using namespace std;

void dfs(int n, int cur, string path, vector<string>& res) {
    if (cur == n) {
        res.push_back(path);
        return;
    }
    for (int i = cur + 1; i <= n; ++i) {
        path += to_string(i);
        dfs(n, i, path, res);
        path.pop_back();
    }
}

int main() {
    int n;
    cin >> n;
    vector<string> res;
    dfs(n, 0, "", res);
    for (string s : res) {
        cout << s << endl;
    }
    return 0;
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-11-21 20:42:08 | 显示全部楼层    本楼为最佳答案   
#include <iostream>
#include <vector>
#include <string>
using namespace std;

void dfs(int n, int cur, string path) {
        //cout << n << " " << cur << " " << path << endl;
        if(cur == n) return;
    for (int i = cur + 1; i <= n; ++i) {
        path += (i+'0');
        cout << path << endl;
        dfs(n, i, path);
        path.erase(path.size()-1, 1);
        }
}

int main() {
    int n;
    cin >> n;
    dfs(n, 0, "");
    return 0;
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-10-7 20:27

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表