[LeetCode]Next Permutation

題目描述:(連接)html

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).code

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

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

1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1leetcode

解題思路:get

轉載連接:http://www.cnblogs.com/easonliu/p/3632442.htmlit

把升序的排列(固然,也能夠實現爲降序)做爲當前排列開始,而後依次計算當前排列的下一個字典序排列。io

對當前排列從後向前掃描,找到一對爲升序的相鄰元素,記爲i和j(i < j)。若是不存在這樣一對爲升序的相鄰元素,則全部排列均已找到,算法結束;不然,從新對當前排列從後向前掃描,找到第一個大於i的元素k,交換i和k,而後對從j開始到結束的子序列反轉,則此時獲得的新排列就爲下一個字典序排列。這種方式實現獲得的全部排列是按字典序有序的,這也是C++ STL算法next_permutation的思想。class

 

連接:http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html,具體過程見註釋

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int i;
        int j;
        // From right to left, find the first item(PartitionNumber) which violate the increase trend
        for (i = nums.size() - 2; i >= 0; --i) {
            if (nums[i] < nums[i + 1]) { break; }
        }
        
        // From right to left, find the first item(ChangeNumber) which is larger than PartitionNumber
        for (j = nums.size() - 1; j >= i ; --j) {
            if (nums[j] > nums[i]) { break; }
        }
        
        // swap PartitionNumber and ChangeNumber
        if (i >= 0) {
            swap(nums[i], nums[j]);
        }
        
        // reverse all after PartitionNumber index
        reverse(nums.begin() + i + 1, nums.end());
    }
};
相關文章
相關標籤/搜索