[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~n 数字的第k个排列

思路1:从小到大生成同时计数,直到第k个。 肯定超时试都不用试。。

思路2:直接根据规律计算第k个排列。

分析:1~n个数共有n!个排列,1开头的有(n-1)!个,2开头的(n-1)!个,...n开头的有(n-1)!个。因此用k/(n-1)!就确定了第一位数字,然后依次类推(用过的数字要去除),继续在(n-1)!个数中找第k%(n-1)!个数。

 

 1 public class Solution {
 2     public String getPermutation(int n, int k) {
 3         String s_n = generateString(n);
 4         int total = factorial(n);
 5         if(n==1 && k==1)
 6             return "1";
 7 
 8         char[] result = new char[n];
 9 
10         for (int i = 0; i < n; ++i) {
11             total /= (n - i);
12             int index = (k - 1) / total;
13             result[i] = s_n.charAt(index);
14             
15             s_n=s_n.replace(result[i]+"", "");
16             k-=index*total;
17         }
18 
19         return new String(result);
20     }
21 
22     private String generateString(int n) {
23         // TODO Auto-generated method stub
24         String sb = "";
25         for (int i = 1; i <= n; ++i) {
26             sb += i + "";
27         }
28         return sb;
29     }
30 
31     private int factorial(int n) {
32         // TODO Auto-generated method stub
33         int total = 1;
34         for (int i = 1; i <= n; i++)
35             total *= i;
36         return total;
37     }
38 }

 

posted @ 2014-09-28 04:14  Phoebe815  阅读(175)  评论(0编辑  收藏  举报