[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

 看了好久才理解这道题的题意。数组中的元素看成一个数,找到下一个比这个数大的一个组合。其实就是用数组中的数组成一个数,把所有组合写出来升序排列,找到排列中一个数的下一个数。

class Solution {
public:
	void nextPermutation(vector<int> &num) {
		vector<int>::iterator it = num.end() - 1;
		while (it != num.begin()){
			if (*(it) > *(it - 1)) break;
			it--;
		}
		if (it != num.begin()){
			it--;
			vector<int>::iterator tmp = num.end() - 1;
			while (*(tmp) <= *(it)) tmp--;
			swap(*(tmp), *(it));
			reverse(it + 1, num.end());
		}
		else{
			reverse(num.begin(), num.end());
		}
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值