[Leetcode]Next Permutation

来源:互联网 发布:手机变声软件女变男 编辑:程序博客网 时间:2024/06/05 05:43

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());}}};


0 0
原创粉丝点击