My clear cpp code with explanation


  • 0
    C
    class Solution {
    public:
        void nextPermutation(vector<int>& nums) 
        {
            if(nums.size() <= 1) return;
            
            // find the first nums[i] < nums[j] from nums's tail
            int i = nums.size() - 2;
            for(; i >= 0; i--)
            {
                if(nums[i] < nums[i+1])
                    break;
            }
            
            // nums is already the largest, reverse back to the smallest
            if(i < 0)
            {
                std::reverse(nums.begin(), nums.end());
                return;
            }
            
            // find the first nums[j] > nums[i]
            int j = nums.size() - 1;
            for(; j > i; j--)
            {
                if(nums[j] > nums[i])
                    break;
            }
            if(j == i) j++;
            
            // swap them
            std::swap(nums[i], nums[j]);
            
            // reverse nums[i+1...end]
            std::reverse(nums.begin()+i+1, nums.end());
        }
    };

Log in to reply
 

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