LeetCode Next Permutation

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,31,3,2
3,2,11,2,3
1,1,51,5,1


STL有这个函数,用时56ms,自己写的是64ms。
重点介绍两个函数,swap和reverse,都写好了,直接用就是。

class Solution {
public:
    void nextPermutation(vector<int> &num) {
    	//STL 自己有这个函数啊
		//next_permutation(num.begin(), num.end());
		if(num.size() <= 1)
			return;
		int first = num.size() - 1;
		while(--first >= 0 && num[first] >= num[first+1]);
		if(first >= 0)
		{
			int second = num.size();
			while(num[--second] <= num[first]);
			if(second < 0)	return;
			swap(num[first], num[second]);
			reverse(num.begin()+first+1, num.end());
		}
		else
		{
			reverse(num.begin(), num.end());
		}
    }
};



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