题目描述:
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 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.
- Given k will be between 1 and n! inclusive.
Example 1:
Input: n = 3, k = 3 Output: "213"
Example 2:
Input: n = 4, k = 9 Output: "2314"
中文理解:
给定两个数组n,k,n表示从1-n的序列组成的数组,k表示排列顺序中的第k个,给1-n数组全排列的第k个排列。
解题思路:
借鉴下一个排列的思想,首先第一个排列为1,2,3,,,n这个序列,然后求k-1次下一个序列,返回即可。
代码(java):
class Solution {
public String getPermutation(int n, int k) {
int[] nums=new int[n];
for(int i=0;i<n;i++){
nums[i]=i+1;
}
for(int i=2;i<=k;i++){
nextPermutation(nums);
}
return intArrayToString(nums);
}
public String intArrayToString(int[] nums){
StringBuilder sb=new StringBuilder();
for(int val:nums){
sb.append(val+"");
}
return sb.toString();
}
public void nextPermutation(int[] nums) {
//从后面找到第一个逆序的
int i=0,j=0;
for(i=nums.length-1;i>0;i--){
if(nums[i]>nums[i-1])break;
}
//得到逆序的下标
i--;
if(i==-1){
reverse(nums,0);
return;
}
//获得从后向前第一个比nums[i]大的数字
for(j=nums.length-1;j>i;j--){
if(nums[j]>nums[i])break;
}
swap(nums,i,j);
reverse(nums,i+1);
}
public void swap(int[]nums,int i,int j){
int temp=nums[i];
nums[i]=nums[j];
nums[j]=temp;
}
public void reverse(int[] nums,int start){
int len=nums.length-1;
while(start<len){
swap(nums,start,len);
start++;
len--;
}
}
}