Next Permutation

  • leetcode 31
  • Medium
  • Company Tags: Google
  • Tags: Array
  • Similar Problems: Permutations, Permutations II, Permutation Sequence, Palindrome Permutation II
Description

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place, do not allocate extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.

1,2,3 → 1,3,2

3,2,1 → 1,2,3

1,1,5 → 1,5,1

Previous Thinking

This problem is not hard in coding after we catch the points.

  1. Scan the array in a reverse order to find out the first position p which violate the ascending order.
  2. Scan the array from the end again to find the first position c which is firstly larger than p.
  3. Exchange the p and c.
  4. Sort the array partially after p.
Java Solution

Java solution is longer than the c++ soluiton. However, easier to understand.

public class Solution {
    public void nextPermutation(int[] nums) {
        if(nums.length < 2) return;

        int p = -1;

        for(int i = nums.length - 1; i > 0; i--){
            if(nums[i] > nums[i - 1]){
                p = i - 1;
                break;
            }
        }

        if( p == -1){
            Arrays.sort(nums);
            return;
        }else{
            int c = -1;
            for(int i = nums.length - 1; i >= 0; i--){
                if(nums[i] > nums[p]){
                    c = i;
                    break;
                }
            }

            swap(nums, p, c);
            Arrays.sort(nums, p + 1, nums.length);
            return;
        }
    }

    void swap(int[] nums, int index1, int index2){
        int temp = nums[index1];
        nums[index1] = nums[index2];
        nums[index2] = temp;
    }


}
C++
class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        auto first=nums.begin();
        auto last=nums.end();
        auto rfirst=reverse_iterator<std::vector<int>::iterator>(last);
        auto rlast=reverse_iterator<std::vector<int>::iterator>(first);

        auto pivot=next(rfirst);

        while(pivot!=rlast && *pivot>=*prev(pivot)) ++pivot;

        if(pivot==rlast){
            reverse(rfirst,rlast);
        }else{
            auto change=find_if(rfirst,pivot,bind1st(less<int>(),*pivot));

        swap(*change,*pivot);
        reverse(rfirst,pivot);
        }
    }
};
Fantastic usage in C++
  1. less<int> is a binary function object whose call return whether the first arguement campares less than the second.
  2. bind1st() is a function which constructs an unary object from the binary function object by binding its first parameter to the fixed value.
  3. find_if find the first position which meets the requirement.

results matching ""

    No results matching ""