386.字典序排数

386.字典序排数

题目描述:

image-20220419231056498

解法:回溯/深度优先搜索

  1. 回溯

回溯代码:

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);
        }
    }
}
  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;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_51134950/article/details/124286417