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

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

 

Solution:

 1 public class Solution {
 2     public String getPermutation(int n, int k) {
 3         if(n==1&&k==1)
 4             return "1";
 5         int total=getTotal(n);
 6         String original=getOriginal(n);
 7         char[] result=new char[n];
 8         for(int i=0;i<n;++i){
 9             total/=(n-i);
10             int t2=(k-1)/total;
11             result[i]=original.charAt(t2);
12             original=original.replace(result[i]+"", "");  //这个方法很巧妙啊,用此法就可以把用过的数字从数组里去掉了!!!
13             k-=t2*total;                                  
14         }
15         return new String(result);
16     }
17 
18     private String getOriginal(int n) {
19         // TODO Auto-generated method stub
20         String result="";
21         for(int i=1;i<=n;++i){
22             result+=i+"";
23         }
24         return result;
25     }
26 
27     private int getTotal(int n) {
28         // TODO Auto-generated method stub
29         int total=1;
30         for(int i=1;i<=n;++i){
31             total*=i;
32         }
33         return total;
34     }
35 }

 

posted @ 2014-11-14 16:22  Phoebe815  阅读(165)  评论(0编辑  收藏  举报