Permutation Sequence

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.

 1 public class Solution {
 2     public String getPermutation(int n, int k) {
 3         int num[] = new int[n];
 4         int per = 1;
 5         for(int i=0;i<n;i++){
 6             num[i] = i+1;
 7             per*=i+1;
 8         }
 9         k--;
10         StringBuilder sb = new StringBuilder();
11         for(int i=n;i>=1;i--){
12             per /=i;
13             int select = k/per;
14             sb.append(num[select]);
15             for(int j=select;j<n-1;j++){
16                 num[j] = num[j+1];
17             }
18             k %=per;
19         }
20         return sb.toString();
21     }
22 }
View Code

 

 

 

posted @ 2014-02-06 14:27  krunning  阅读(99)  评论(0编辑  收藏  举报