题目描述:
https://leetcode.com/problems/next-permutation/
解决方案:
https://leetcode.com/problems/next-permutation/solution/
mycode(c++):
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int i = nums.size() - 2;
while (i >= 0 && nums[i + 1] <= nums[i]) {
i--;
}
if (i >= 0) {
int j = nums.size()- 1;
while (j >= 0 && nums[j] <= nums[i]) {
j--;
}
swap(nums, i, j);
}
reverse(nums, i + 1);
}
void reverse(vector<int>& nums, int start) {
int i = start, j = nums.size() - 1;
while (i < j) {
swap(nums, i, j);
i++;
j--;
}
}
void swap(vector<int>& nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
};
心得:
重点是对于题目的理解,详解见下
https://leetcode.windliang.cc/leetCode-31-Next-Permutation.html