[LeetCode] Next Permutation

2014-11-24 02:30:38 · 作者: · 浏览: 4
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
问题描述:重新排列数字,得到按大小排列的下一个数字,如果没有这样的排列,也就是说不能得到比它还大的,就按照升序重新排列。
要求必须原地进行,不能分配额外空间。
方法是,从后面往前面遍历,假设当前比较的后面的值是a,前面的值是b,如果b>=a,则继续遍历,如果b
=a,则重新按照升序排列。
class Solution {  
public:  
    void nextPermutation(vector &num) {  
        // IMPORTANT: Please reset any member data you declared, as  
        // the same Solution instance will be reused for each test case.  
        int tmp = 0;  
        vector::iterator iter, viter;  
  
        for(viter = num.end()-1;  
                                  viter != num.begin(); --viter) {  
            if(*viter > *(viter-1)) {  
                iter = viter;  
                while(iter != num.end() && *iter > *(viter-1))  
                    ++iter;  
                --iter;  
                tmp = *iter;  
                num.erase(iter);  
                iter = num.insert(viter-1, tmp);  
                sort(iter+1, num.end());  
                break;  
            }  
        }  
  
        if(viter == num.begin()) {  
            sort(num.begin(), num.end());  
        }  
    }  
};