My iterative 12ms C++ solution.


  • 2
    A
    void nextPermutation(vector<int>& nums) {
        int n = nums.size() - 1;
        int i;
        for (i = n - 1; i >= 0; i--) {
            if (nums[i] < nums[i + 1]) {
                sort(nums.begin() + i + 1, nums.end());
                int j;
                //it would be better to use some modified
                //binary search here but ...)
                for (j = i + 1; nums[j] <= nums[i]; j++) {}
                swap(nums[j], nums[i]);
                break;
            }
        }
        if (i < 0) {
            sort(nums.begin(), nums.end());
        }
    }

Log in to reply
 

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