还是使用之前用过多次的nextPermutation方法。。。(几乎所有跟排列相关的题都是同一个题- -)
class Solution {
public String getPermutation(int n, int k) {
int[] nums = new int[n];
for (int i = 1; i <= n; i++) {
nums[i - 1] = i;
}
while (k > 1) {
nextPermutation(nums);
k--;
}
StringBuilder ans = new StringBuilder();
for (int num : nums) {
ans.append(num);
}
return ans.toString();
}
// 当没有下一个排列时return false
public boolean nextPermutation(int[] nums) {
if (nums.length == 1) {
return false;
}
int p = -1;
for (int i = nums.length - 2; i >= 0; i--) {
if (nums[i] < nums[i + 1]) {
p = i;
break;
}
}
if (p != -1) {
int tmp = nums[p];
int q = nums.length - 1;
while (nums[q] <= tmp) {
q--;
}
nums[p] = nums[q];
nums[q] = tmp;
reverse(p + 1, nums);
} else {
// reverse(0, nums);
return false;
}
return true;
}
public void reverse(int k, int[] nums) {
if (k >= nums.length) return;
int i = k;
int j = nums.length - 1;
while (i < j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
i++;
j--;
}
}
}