您的位置:首页 > 其它

LeetCode 31. Next Permutation

2016-11-03 18:18 423 查看
题目描述

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) {
if (num.size() < 2) return;

int i, k;
for (i = num.size() - 2; i >= 0; --i)
if (num[i] < num[i + 1])
break;

if (i < 0)
{
reverse(num.begin() , num.end());
return;
}

for (k = num.size() - 1; i >= 0 && k > i ; --k)
if (num[i] < num[k])
break;
if (i >= 0)
{
swap(num[i], num[k]);
reverse(num.begin() + i + 1, num.end());
return;
}

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: