Easy C++ solution


  • 0
    A
    class Solution {
    public:
        void nextPermutation(vector<int>& nums) {
            for (int i = nums.size() - 2; i >= 0; i--) {
                if (canMove(nums, i)) {
                    return;
                }
            }
            reverse(nums.begin(), nums.end());
        }
        
        bool canMove(vector<int>& nums, int from) {
            for (int next = nums.size() - 1; next > from; next--) {
                if (nums[next] > nums[from]) {
                    swap(nums[from], nums[next]);
                    reverse(nums.begin() + from + 1, nums.end());
                    return true;
                }
            }
            return false;
        }
    };
    

Log in to reply
 

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