字典序排序

主要是關於LeetCode當中的字典序排序問題

  • 386 Lexicographical Numbers
  • 440 字典序的第K小數字
  • 524 通過刪除字母匹配到字典裏面最長單詞
  • 361 去除重複字母使得剩下的字典排序最小的情況

386 字典序排序算法

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].

給 30
1,10,11,12,13,14,15,16,17,18,19, 2,20,

解決步驟

  1. 先爭取*10,看是否滿足
  2. 末尾小於9,不是9 (取餘操作),滿足++1操作
  3. 回退操作, 處理末尾爲9 ,在這裏面還要處理一個就是連續的末尾爲9,比如 49999, 最終要處理成爲49

// 49999 49 這兩種方式都要處理成爲 5 , 只是對應的n 取值不是一樣的基本情況

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].

非stack 方法

public class Solution{
   public List<Integer> sloved(int n){
   List<Integer> result =new LinkedList<>();
        if(n==0) return result;
        int current =1;
        // 0````00 一共有n 位可以取值的基本情況
        for(int i=1;i<=n;i++){
            result.add(current);
            // 如果可以一直*到10000000000, 1位
            
            if(current*10<=n){
            //  在後面加一個10,, 比如1 ,n=10, 我們就可以10 
                
                // 1, 10 
                current *=10;
            }
            //以數字9結尾的數字不能進行++操作,等基本概念
            // ++1 的邊界條件
            else if (current+1<=n && current%10!=9) {
                current++;
            }
            // 進行回退操作  比如 n=550, 現在是499 ,不能加1操作, 加1就是500 漏了5這些
            // 所以需要進行一個回退操作
            // 將499這樣的數據進行回退, 449  轉變成爲5  499, 49  
            // 897  89 
            else{
                // 處理連續的9999   比如 499999 最終進過while 循環變成49的基本情況
                while((current/10)%10==9)
                {
                    current /=10;
                }
                // while 循環只能把499 變換我49 ,最後我們還是需要最後一步進行處理
                //將49轉換爲5
                // 
                current = current/10 +1;
            }
            
        }
        return result;
    }
   }
}

DFS

class Solution {
    public List<Integer> lexicalOrder(int n) {
        List<Integer> result =new LinkedList<>();
        if(n==0) return result;
        // 所有的數字
        // 分別從1,2,3,4,5,6,7,8 9,這些數字開回溯
//For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9].

        for(int i=1;i<10;i++){
            dfs(n,i,result);
        }
        return result;
    }
    private void dfs(int n, int current, List<Integer> result){
        // 剪紙的基礎條件情況
        if(current>n)
            return;
    
        result.add(current);
        current *=10;
        for(int i=0;i<10;i++){
                // 進一步進行深度有效搜索
               if(current+i>n)
                    return;
              dfs(n,current+i,result);
            
        }
    }
    
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章