题目描述:
解法:回溯/深度优先搜索
- 回溯
回溯代码:
class Solution {
public List<Integer> lexicalOrder(int n) {
backtrack(n);
return rest;
}
List<Integer> rest = new ArrayList<>();
StringBuilder sb = new StringBuilder();
void backtrack(int n){
for(int i = 0; i <= 9; i++){
sb.append(i);
Integer v = Integer.valueOf(sb.toString());
if(v < 1 || v > n){
sb.deleteCharAt(sb.length() - 1);
continue;
}
rest.add(v);
backtrack(n);
sb.deleteCharAt(sb.length() - 1);
}
}
}
- 深度优先搜索
class Solution {
public List<Integer> lexicalOrder(int n) {
List<Integer> rest = new ArrayList<>();
int num = 1;
for(int i = 1; i <= n; i++){
rest.add(num);
if(num * 10 <= n){
num *= 10;
} else {
while(num % 10 == 9 || num + 1 > n){
num /= 10;
}
num += 1;
}
}
return rest;
}
}