[LeetCode] 31. Next Permutation 下一個排列

 

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

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

The replacement must be in-place and use only constant extra memory.github

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,1post

 

這道題讓咱們求下一個排列順序,由題目中給的例子能夠看出來,若是給定數組是降序,則說明是全排列的最後一種狀況,則下一個排列就是最初始狀況,能夠參見以前的博客 Permutations。再來看下面一個例子,有以下的一個數組url

1  2  7  4  3  1spa

下一個排列爲:code

1  3  1  2  4  7htm

那麼是如何獲得的呢,咱們經過觀察原數組能夠發現,若是從末尾往前看,數字逐漸變大,到了2時才減少的,而後再從後往前找第一個比2大的數字,是3,那麼咱們交換2和3,再把此時3後面的全部數字轉置一下便可,步驟以下:blog

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());
    }
};

 

Github 同步地址:

https://github.com/grandyang/leetcode/issues/31

 

相似題目:

Permutations II

Permutations

Permutation Sequence

Palindrome Permutation II 

Palindrome Permutation

 

參考資料:

https://leetcode.com/problems/next-permutation/

https://leetcode.com/problems/next-permutation/discuss/13921/1-4-11-lines-C%2B%2B

https://leetcode.com/problems/next-permutation/discuss/13867/C%2B%2B-from-Wikipedia

 

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

相關文章
相關標籤/搜索