鱼C论坛

 找回密码
 立即注册
查看: 580|回复: 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
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. using namespace std;

  5. void dfs(int n, int cur, string path) {
  6.         //cout << n << " " << cur << " " << path << endl;
  7.         if(cur == n) return;
  8.     for (int i = cur + 1; i <= n; ++i) {
  9.         path += (i+'0');
  10.         cout << path << endl;
  11.         dfs(n, i, path);
  12.         path.erase(path.size()-1, 1);
  13.         }
  14. }

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

使用道具 举报

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

  5. void dfs(int n, int cur, string path, vector<string>& res) {
  6.     if (cur == n) {
  7.         res.push_back(path);
  8.         return;
  9.     }
  10.     for (int i = cur + 1; i <= n; ++i) {
  11.         path += to_string(i);
  12.         dfs(n, i, path, res);
  13.         path.pop_back();
  14.     }
  15. }

  16. int main() {
  17.     int n;
  18.     cin >> n;
  19.     vector<string> res;
  20.     dfs(n, 0, "", res);
  21.     for (string s : res) {
  22.         cout << s << endl;
  23.     }
  24.     return 0;
  25. }
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

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

  5. void dfs(int n, int cur, string path) {
  6.         //cout << n << " " << cur << " " << path << endl;
  7.         if(cur == n) return;
  8.     for (int i = cur + 1; i <= n; ++i) {
  9.         path += (i+'0');
  10.         cout << path << endl;
  11.         dfs(n, i, path);
  12.         path.erase(path.size()-1, 1);
  13.         }
  14. }

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

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-5-1 03:31

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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