標籤:
原題連結在這裡: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