leetcode#31 next permutation

mplement 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 and use only constant 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


template<class BidirIt>
bool next_permutation(BidirIt first, BidirIt last)
{
    if (first == last) return false;
    BidirIt i = last;
    if (first == --i) return false;
 
    while (true) {
        BidirIt i1, i2;
 
        i1 = i;
        if (*--i < *i1) {
            i2 = last;
            while (!(*i < *--i2))
                ;
            std::iter_swap(i, i2);
            std::reverse(i1, last);
            return true;
        }
        if (i == first) {
            std::reverse(first, last);
            return false;
        }
    }
}

class Solution {
public:
    void nextPermutation(vector<int>& num)
    {
        next_permutation(num.begin(),num.end());
    }
    
};
class Solution {
public:
    //其实应该看看stl的实现
    void nextPermutation(vector<int>& num)
    {
        int i, j, n = num.size();
        for (i = n - 2; i >= 0; --i)
        {
            if (num[i + 1] > num[i]) //从右到左找到第一个降序 1 2 7 4 3 1,也就是num[i+1]=7
            {
                for (j = n - 1; j > i; --j) //找比num[i]=2大的数
                {
                    if (num[j] > num[i]) //num[j]=3
                        break;
                }
                swap(num[i], num[j]);//交换2,3->137421
                reverse(num.begin() + i + 1, num.end());//131247
                return;
            }
        }
        reverse(num.begin(), num.end());        
    }
};

猜你喜欢

转载自www.cnblogs.com/lsaejn/p/9724575.html
今日推荐