Super consice C++ solution.


  • 2
    H
    class Solution {
    public:
        void nextPermutation(vector<int>& nums) {
            // search backward and find the first element satisfying
            // nums[i] < nums[i + 1].
            int begin = nums.size() - 2;
            while (begin >= 0) {
                if (nums[begin] < nums[begin + 1]) {
                    break;
                }
                --begin;
            }
            // generate next permutation!
            reverse(nums.begin() + begin + 1, nums.end());
            if (begin >= 0) {
                int next = begin + 1;
                while (nums[begin] >= nums[next]) {
                    ++next;
                }
                swap(nums[begin], nums[next]);            
            }
        }
    };

Log in to reply
 

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