题意
给出一个n,将前n个数字按照字典序排序后输出。
思路
dfs。从小到大循环一下当前位置应该放的数字即可。
注意前导0。
代码
class Solution {
private:
vector<int> a;
int n;
public:
void dfs(int x, int step) {
if (x > n) return;
if (x) a.push_back(x);
for (int i = (step ? 0 : 1); i < 10; i++) {
dfs(x * 10 + i, step + 1);
}
}
vector<int> lexicalOrder(int n) {
this->n = n;
dfs(0, 0);
return a;
}
};

本文介绍了一种使用深度优先搜索(DFS)实现的算法,该算法可以将从1到n的所有整数按照字典序进行排序。通过递归地构建数字,确保了每个可能的数字都被考虑,并且有效地处理了前导零的问题。
4208

被折叠的 条评论
为什么被折叠?



