Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

31. Next Permutation leetcode solution in c++

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int n=nums.size()-1;
        bool flag=false;
        for(int i=0;i<n;i++)
        {
            if(nums[i]<nums[i+1])
            {
                flag=true;
                break;
            }
        }
        //check
        if(flag)
        {
            int k;
            for(int i=n-1;i>=0;i--)
            {
                if(nums[i]<nums[i+1])
                {
                    k=i;
                    break;
                }
            }
            int j;
            for(int i=n;i>k;i--)
            {
                if(nums[i]>nums[k])
                {
                    j=i;
                    break;
                }
            }
            swap(nums[k],nums[j]);
            reverse(nums.begin()+k+1,nums.end());
        }else
        {
            reverse(nums.begin(),nums.end());
        }
    }
};
Source by www.codegrepper.com #
 
PREVIOUS NEXT
Tagged: #Next #Permutation #leetcode #solution
ADD COMMENT
Topic
Name
8+9 =