public String getPermutation(int n, int k) {
int[] nums = new int[n];
for(int i = 0;i < n;i++){
nums[i] = i+1;
}
int nTemp = n;
int kTemp = k;
for(int i = 0;i<n-1;i++){
int mod = kTemp % cal(nTemp-1);
int quotient = kTemp /cal(nTemp-1);
if(mod == 0){
swap(nums,i,i+quotient-1);
kTemp = cal(nTemp-1);
}else{
swap(nums,i,i+quotient);
kTemp = mod;
}
insertsort(nums,i+1,n-1);
nTemp--;
}
StringBuilder str = new StringBuilder();
for (int i = 0; i < n; i++) {
str.append(nums[i]);
}
return new String(str);
}
private void swap(int[]nums,int i,int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
private int cal(int n){
int res = 1;
for(int i = 1;i<=n;i++){
res*=i;
}
return res;
}
private void insertsort(int[]nums,int start,int end){
int j = 0;
for(int i = start+1;i<=end;i++){
int key = nums[i];
for(j = i-1;j>=start;j--){
if(nums[j]>key){
nums[j+1] = nums[j];
}else{
break;
}
}
nums[j+1] = key;
}
}
leetcode 下一个排列
最新推荐文章于 2022-07-04 14:33:24 发布