您的位置:首页 > 其它

LeetCode 31 Next Permutation

2017-02-16 16:08 435 查看
题意:

给出一串数字,求该排列的下一个排列。如果该排列为字典序最大排列,则输出字典序最小排列。

思路:

首先C++里面有求下一个排列的函数next_permutation,该函数返回0即表示当前排列字典序最大。

如果要自己动手实现,那么就考虑“如何找到比当前排列大1的排列”。

假设排列A(aaaXddd)比排列B(aaaYfff)大1,a部分为两排列相同部分,X与Y表示最靠左边不同的那一位。那么,X>Y且X一定在B中的f部分且f中数字一定是递减排序的且d一定是递增排序的。

代码:

class Solution {
public:
void nextPermutation(vector<int> &nums) {
int idx = findPos(nums);
if (idx == -1) {
reverse(nums.begin(), nums.end());
} else {
reverse(nums.begin() + idx + 1, nums.end());
for (int i = idx + 1; i < nums.size(); ++i) {
if (nums[idx] < nums[i]) {
swap(nums[idx], nums[i]);
break;
}
}
}
}

private:
int findPos(vector<int> &nums) {
for (int i = nums.size() - 2; i >= 0; --i) {
if (nums[i] < nums[i + 1]) {
return i;
}
}
return -1;
}
};

/**
* 偷懒版本……
*/

class Solution {
public:
void nextPermutation(vector<int> &nums) {
if (!next_permutation(nums.begin(), nums.end())) {
sort(nums.begin(), nums.end());
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: