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 and use only constant 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,23,2,1 → 1,2,31,1,5 → 1,5,1
Question idea:
if this order not the biggest one,such as 3 2 1,let it be the bigger one.If the biggest change into smallest.
#include<stdio.h> #include<iostream> #include<vector> #include<algorithm> using namespace std; class Solution { public: void nextPermutation(vector<int>& nums) { //if(nums.size()<=1) return; //if(nums.size()==2&&nums[0]==nums[1]) return; int i=nums.size()-2; while(i>=0&&nums[i]>nums[i+1]) { i--; } if(i>=0) { int j=nums.size()-1; while(i<=j&&nums[i]>=nums[j]) { j--; } swap(nums[i],nums[j]); } reverse(nums.begin()+i+1,nums.end()); } }; int main() { vector<int> input; input.push_back(1); input.push_back(5); input.push_back(1); Solution s; s.nextPermutation(input); for(auto t:input) { cout<<t<<endl; } return 0; }
The important point is & in the nextPermutation function.If you not add & only change "copy",but add & will change the array itself.
swap and reverse function really helps a lot! need to add #include<algorithm> in the front
32.
useful website:
https://blog.csdn.net/weixin_38823568/article/details/80997966
https://zxi.mytechroad.com/blog/stack/leetcode-32-longest-valid-parentheses/
浙公网安备 33010602011771号