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

leetCode 60.Permutation Sequence (排列序列) 解题思路和方法

2015-07-15 14:16 561 查看
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的值,学过排列组合知道共有n!种排列。

第一位每个数字开头的序列都有(n-1)!个序列,因此n个数字所以共有n!个序列。

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

具体代码如下:

public class Solution {
String str = "";
public String getPermutation(int n, int k) {
int[] num = new int
;
int[] data = new int
;//存阶乘的数据
int i = 0;
for(; i < n ;i++){
num[i] = i+1;
if(i == 0)
data[i] = 1;
else{
data[i] = data[i-1]*i;
}
}
k--;
while(--i > -1){//循环得到各位数字
int k1 = k/data[i];
int p = k1+(n-1-i);//数字的位置
swap(n-1-i,p,num);
if((k = k %data[i]) == 0)//k==0结束
break;
}
for(int x:num)//得到str
str += x;
return str;
}
//将数据插入,后面的依次后移
public void swap(int i,int j,int[] num)
{
int m = num[j];
for(int k=j;k>i;k--)
num[k]=num[k-1];
num[i]=m;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: