Leetcode#31 Next Permutation

1 minute read

Published:

https://leetcode.com/problems/next-permutation/description/

Idea:

  1. From right to left, find the first digit(partitionNumber) which violates the increase trend
  2. If not found, it means the current sequence is already the largest permutation
  3. From right to left, find the first digit which is greater than the partition number, call it changeNumber. Swap changeNumber and partitionNumber.
  4. Reverse all digits on the right of partitionNumber

Solution:

class Solution {
    public:
        void nextPermutation(vector<int>& nums) {
            if (nums.size() <= 1)
                return;

            int i=nums.size()-1;

            /* From right to left, find the first digit(partitionNumber) which violates the increase trend */
            while(i>0) {
                if (nums[i] <= nums[i-1]) {
                    i--;
                } else {
                    break;
                }
            }

            cout<<i<<endl;
            /* If not found, it means the current sequence is already the largest permutation */
            if(i==0) {
                reverse(nums, 0, nums.size()-1);
                return;
            }

            /* From right to left, find the first digit which is greater than the partition number, call it changeNumber */
            for(int j=nums.size()-1; j>=i; j--) {
                if(nums[j]>nums[i-1]) {
                    /* swap */
                    int tmp = nums[i-1];
                    nums[i-1] = nums[j];
                    nums[j] = tmp;
                    break;
                }
            }

            /* Reverse all digits  on the right of partitionNumber */
            reverse(nums, i, nums.size()-1);
            return;
        }

        void reverse(vector<int>& nums, int begin, int end) {
            while(end >= begin) {
                int tmp = nums[end];
                nums[end] = nums[begin];
                nums[begin] = tmp;
                begin++;
                end--;
            }
        }
};