您的位置:首页 > 产品设计 > UI/UE

Permutation Sequence

2015-10-03 20:11 375 查看
题目:

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):

"123"

"132"

"213"

"231"

"312"

"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
;
StringBuilder buf = new StringBuilder("");

int[] res = new int
;
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();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: