Permutation Sequence

来源:互联网 发布:淘宝客是做什么的 编辑:程序博客网 时间:2024/06/09 21:19

题目:

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-1)!个序列,因此n个数字所以共有n!个序列。

以此类推,第二位每一个数开头都有(n-2)!个序列。

参考代码如下:

http://www.programcreek.com/2013/02/leetcode-permutation-sequence-java/

public class Solution {public String getPermutation(int n, int k) {boolean[] output = new boolean[n];StringBuilder buf = new StringBuilder(""); int[] res = new int[n];res[0] = 1; for (int i = 1; i < n; i++)res[i] = res[i - 1] * i; for (int i = n - 1; i >= 0; i--) {int s = 1; while (k > res[i]) {s++;k = k - res[i];} for (int j = 0; j < n; j++) {if (j + 1 <= s && output[j]) {s++;}} output[s - 1] = true;buf.append(Integer.toString(s));} return buf.toString();}}

第二种:

public String getPermutation(int n, int k) {    if(n<=0)        return "";    k--;    StringBuilder res = new StringBuilder();    int factorial = 1;    ArrayList<Integer> nums = new ArrayList<Integer>();    for(int i=2;i<n;i++)    {        factorial *= i;    }    for(int i=1;i<=n;i++)    {        nums.add(i);    }    int round = n-1;    while(round>=0)    {        int index = k/factorial;        k %= factorial;        res.append(nums.get(index));        nums.remove(index);        if(round>0)            factorial /= round;        round--;    }    return res.toString();}



0 0