C++ simple solution


  • 0
    J
    class Solution {
    public:
        void nextPermutation(vector<int>& nums) {
            int len=nums.size();
            int savei=-1;
            int savej=-1; //save the largest position to be swapped
            for(int i=len-1; i>0; i--)
            {
                for(int j=i-1; j>=0; j--)
                {
                    if(nums[i]>nums[j])
                    {
                        if(savej<j)
                        {
                            savej=j;
                            savei=i;
                        }
                       
                    }
                }
            }
            swap(nums[savei], nums[savej]);
            sort(nums.begin()+savej+(savej==-1?0:1), nums.end());
        
        }
    };
    

Log in to reply
 

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