LeetCode Permutation Sequence

來源:互聯網
上載者:User

標籤:

原題連結在這裡:https://leetcode.com/problems/permutation-sequence/

原理是n個數有n!個permutation, 那麼n-1個數就有(n-1)!種排列, n可以分成n組,每組有(n-1)!個數.

比如n = 6,那麼以1,2,3,4,5,6開頭的組合必然是各有(n-1)! = 5! = 120中組合, 若K = 299,那麼我們先要求解這個k在第幾組,k/(n-1)! = 299/120 = 2,也就是說k應該在第

3組(注意組號從0開始),組數應該從0開始,那麼k要-1; 第三組的首個數字應該是3,第一個數字就確定了。

確定第2個數位時候,注意這個時候,k應該等於k % 120 = 59,為什麼要這麼算呢,因為每個組有120個數字,

而且k在第三組,那麼前兩組加起來是240,k在第二次迴圈的時候,應該是從(5-1)!中確定是屬於哪個組,其實就是確定k在第三組中是屬於哪個位置。

這個時候59/24 = 2,確定應該是屬於第三組,因為在上一步中,3已經用過了,所以這個時候的5個數字是1,2,4,5,6,所以第三組的首個數字是4,依次類推,一直到n個數字全部算完為止。

因為前面的數被拿掉後後面的數字要跟上,所以使用list結構。

AC Java:

 1 public class Solution { 2     public String getPermutation(int n, int k) { 3         if(n<=0 || k<=0){ 4             return ""; 5         } 6          7         k--; 8         int factorial = 1; 9         List<Integer> ls = new ArrayList<Integer>();10         for(int i = 1; i<=n; i++){11             ls.add(i);12         }13         for(int i = 1; i<n; i++){14             factorial *= i;15         }16         17         StringBuilder sb = new StringBuilder();18         int counter = n-1;19         while(counter>=0){20             int index = k/factorial;21             sb.append(ls.get(index));22             ls.remove(index);23             24             k%=factorial;25             if(counter != 0){26                 factorial /= counter;27             }28             counter--;29         }30         return sb.toString();31     }32 }

 

LeetCode Permutation Sequence

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.