Simple C++ code with explanation


  • 1
    L
    class Solution {
    public:
        void nextPermutation(vector<int>& nums) {
            int n = nums.size();
            if (!n)
                return;
            int i = n - 2;
            while (i >= 0 && nums[i] >= nums[i+1])
                i--;
            if (i != -1) {
                for (int j = n - 1; j > i; j--)
                    if (nums[j] > nums[i]) {
                        swap(nums[j], nums[i]);
                        break;
                    }
            }
            reverse(nums.begin() + i + 1, nums.end());
        }
    };
    
    1. find the first nums[i] < nums[i+1].

    2. swap nums[i] and nums[j], where j >i is the largest index that nums[j] > nums[i].

    3. reverse from i + 1 to the end.


  • 0
    J

    Thanks for your sharings.I understand it.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.