Next Permutation

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

基本思路:

1、从后往前找第一个相邻逆序对(从左往右看),标记逆序对的起始位置i-1。如果没找到,直接跳到第3步。

2、再一次从后往前找第一个比num[i-1]大的数,下标为j,交换num[i-1],num[j]。此时,从i 到len-1的数应该还是递减数列,将这个递减数列逆转一下就好了,reverse(num,i,j)

3、前面如果没有找到逆序对,则逆转整个序列。

class Solution {
public:
void swap(int &a ,int &b){
        int temp = a;
        a = b;
        b = temp;
        
    }
    
    void reverse(vector<int> & num , int start , int end){
        while(start < end){
            swap(num[start] , num[end]);
            start ++ ;
            end --;
        }
    }
    void nextPermutation(vector<int> &num) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        
        int len = num.size();
        if(len <= 1)
            return ;
        bool changed = false;
        for(int i = len -1 ; i > 0;i -- ){
			if(num[i] >num[i-1]){
				int j = len -1;
				for( ; j > i -1;j -- )
					if(num[j] > num[i-1])
						break;				
				swap(num[i-1],num[j]);
				reverse(num,i,len -1);
				changed = true;
				break;
				} 		
        }
        if(changed)
            return;
        else{
            reverse(num,0, len -1);
            return;
        }
        
    }
};




你可能感兴趣的:(Next Permutation)