From : https://leetcode.com/problems/next-permutation/
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place, do not allocate extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
Hide Similar Problems
Solution :
class Solution {
public:
void swap(int &a, int &b) {
int t = a;
a = b;
b = t;
}
void swap(vector<int> &nums, int start, int end) {
while(start < end) {
swap(nums[start++], nums[end--]);
}
}
void nextPermutation(vector<int>& nums) {
int len=nums.size(), j=len-2, k;
// find the last sequential pair
while(j >= 0) {
if(nums[j] < nums[j+1]) break;
else j--;
}
if(j == -1) {
// when no inverse order, reverse and return
swap(nums, 0, len-1);
return;
}
// find the last sequential partner with j
for(int i=j+1; i<len; i++) {
if(nums[i] > nums[j]) k = i;
}
swap(nums[j], nums[k]);
// swap the rest
swap(nums, j+1, len-1);
}
};
public class Solution {
public void nextPermutation(int[] nums) {
int len = nums.length, j = len-2, k = len-1;
// find the last sequential pair
while(j>=0 && nums[j]>=nums[j+1]) --j;
if(j == -1) {
swapAll(nums, 0, len-1);
return;
}
// find the last sequential partner with j
for(int n=nums[j]; n>=nums[k]; --k) {}
swap(nums, k, j);
swapAll(nums, j+1, len-1);
}
private void swap(int[] nums, int i, int j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
private void swapAll(int[] nums, int i, int j) {
while(i < j) {
swap(nums, i++, j--);
}
}
}
本文深入探讨了如何实现下一个排列算法,通过一系列实例解析,帮助开发者理解和掌握该算法的实现细节,包括如何在原地操作数组以生成下一个可能的排列。
421

被折叠的 条评论
为什么被折叠?



