[LeetCode] Next Permutation 下一個排列

Grandyang發表於2015-04-15

 

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

 

這道題讓我們求下一個排列順序,有題目中給的例子可以看出來,如果給定陣列是降序,則說明是全排列的最後一種情況,則下一個排列就是最初始情況,可以參見之前的部落格 Permutations 全排列。我們再來看下面一個例子,有如下的一個陣列

1  2  7  4  3  1

下一個排列為:

1  3  1  2  4  7

那麼是如何得到的呢,我們通過觀察原陣列可以發現,如果從末尾往前看,數字逐漸變大,到了2時才減小的,然後我們再從後往前找第一個比2大的數字,是3,那麼我們交換2和3,再把此時3後面的所有數字轉置一下即可,步驟如下:

1  2  7  4  3  1

1  2  7  4  3  1

1  3  7  4  2  1

1  3  1  2  4  7

 

解法一:

class Solution {
public:
    void nextPermutation(vector<int> &num) {
        int i, j, n = num.size();
        for (i = n - 2; i >= 0; --i) {
            if (num[i + 1] > num[i]) {
                for (j = n - 1; j > i; --j) {
                    if (num[j] > num[i]) break;
                }
                swap(num[i], num[j]);
                reverse(num.begin() + i + 1, num.end());
                return;
            }
        }
        reverse(num.begin(), num.end());
    }
};

 

下面這種寫法更簡潔一些,但是整體思路和上面的解法沒有什麼區別,參見程式碼如下:

 

解法二:

class Solution {
public:
    void nextPermutation(vector<int>& nums) {int n = nums.size(), i = n - 2, j = n - 1;
        while (i >= 0 && nums[i] >= nums[i + 1]) --i;
        if (i >= 0) {
            while (nums[j] <= nums[i]) --j;
            swap(nums[i], nums[j]);
        }
        reverse(nums.begin() + i + 1, nums.end());
    }
};

 

類似題目:

Permutations II

Permutations

 

參考資料:

https://discuss.leetcode.com/topic/30212/easiest-java-solution

 

LeetCode All in One 題目講解彙總(持續更新中...)

相關文章