# [leetcode] 60. 第k个排列

60. 第k个排列

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--;
}
}
}
posted @ 2018-07-23 23:43  ACBingo  阅读(...)  评论(...编辑  收藏