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());
}
}
};
本文介绍了一个算法问题——如何在原地实现数组元素的下一个字典序排列。通过具体示例和代码解析,阐述了寻找并生成下一个更大排列的方法,当无法生成更大的排列时则将数组按升序排列。
421

被折叠的 条评论
为什么被折叠?



