LeetCode 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

题意:给出一个数组,求其下一个排列

思路:从右到左找到a[i] < a[i+1],然后从尾到i之间找到a[j]< a[i],交换a[i],a[j],然后j到尾反转

代码如下:

class Solution {
public:
    void nextPermutation(vector& nums) {
        int len = nums.size();
		if (len <= 1) return;

		int i = len - 1;
		i--;

		while (1) {
			if (i < 0) {
				reverse(nums.begin(), nums.end());
				break;
			}

			if (nums[i] < nums[i + 1]) {
				int j = len - 1;
				while (!(nums[i] < nums[j])) j--;
				swap(nums[i], nums[j]);
				vector::iterator it = nums.begin();
				advance(it, i + 1);
				reverse(it, nums.end());
				break;
			}
			i--;
		}
    }
};


你可能感兴趣的:(#,#,数论)