程序
描述走楼梯时,后面的跨步要求大于前面的跨步,最大一次允许跨n级。任意走几步,有几种走法
输入
正整数n(n<10)
输出
多行,每行表示一种走法
样例输入
3
样例输出
1
12
123
13
2
23
3
C++ #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;
}
#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;
}
页:
[1]