Lexicographical Numbers 386
Question
Given an integer n, return 1 - n in lexicographical order.
For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9].
Please optimize your algorithm to use less time and space. The input size may be as large as 5,000,000.
Solution
典型的backtrack问题。不断 * 10直到大于n,再返回上一层继续往下一个数。
代码如下:
public class Solution {
public List<Integer> lexicalOrder(int n) {
List<Integer> res = new ArrayList<Integer>();
for (int i = 1; i < 10; i++) {
dfs(n, i, res);
}
return res;
}
private void dfs(int n, int curt, List<Integer> res) {
if (curt > n) {
return;
}
res.add(curt);
for (int i = 0; i < 10; i++) {
if (curt * 10 + i > n) {
return;
} else {
dfs(n, curt * 10 + i, res);
}
}
}
}