Permutation Sequence leetcode java


題目

The set [1,2,3,…,n] contains a total of n! unique permutations.

By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):

  1. "123"
  2. "132"
  3. "213"
  4. "231"
  5. "312"
  6. "321"

Given n and k, return the kth permutation sequence.

Note: Given n will be between 1 and 9 inclusive.

 

題解:

發現數學規律。

首先先捋捋這道題要干啥,給了我們n還有k,在數列 1,2,3,... , n構建的全排列中,返回第k個排列。

題目告訴我們:對於n個數可以有n!種排列;那么n-1個數就有(n-1)!種排列。

那么對於n位數來說,如果除去最高位不看,后面的n-1位就有 (n-1)!種排列。

所以,還是對於n位數來說,每一個不同的最高位數,后面可以拼接(n-1)!種排列。

所以你就可以看成是按照每組(n-1)!個這樣分組。

利用 k/(n-1)! 可以取得最高位在數列中的index。這樣第k個排列的最高位就能從數列中的index位取得,此時還要把這個數從數列中刪除。

然后,新的k就可以有k%(n-1)!獲得。循環n次即可。

 同時,為了可以跟數組坐標對其,令k先--。

 

代碼如下:

 

 1      public String getPermutation( int n,  int k) {  
 2         k--; // to transfer it as begin from 0 rather than 1
 3          
 4         List<Integer> numList =  new ArrayList<Integer>();  
 5          for( int i = 1; i<= n; i++)
 6             numList.add(i);
 7        
 8          int factorial = 1;    
 9          for( int i = 2; i < n; i++)  
10             factorial *= i;    
11         
12         StringBuilder res =  new StringBuilder();
13          int times = n-1;
14          while(times>=0){
15              int indexInList = k/factorial;
16             res.append(numList.get(indexInList));  
17             numList.remove(indexInList);  
18             
19             k = k%factorial; // new k for next turn
20               if(times!=0)
21                 factorial = factorial/times; // new (n-1)!
22              
23             times--;
24         }
25         
26          return res.toString();
27     } 

 

Reference:

http://blog.csdn.net/linhuanmars/article/details/22028697

http://blog.csdn.net/fightforyourdream/article/details/17483553

http://blog.csdn.net/u013027996/article/details/18405735


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM