您的位置:首页 > 编程语言 > C语言/C++

Leetcode Next Permutation

2015-10-23 12:11 519 查看
Leetcode Next Permutation ,通过查看排列的特性,可以发现,每一次改变值的位置之后的元素都是按升序排列的,如:arr = [5, 4, 2, 3, 1],可以知道其下一个排列为:brr = [5, 4, 3, 1, 2],对于arr可以发现元素“2”后面元素为降序排列,那么如果要生成下一个序列,就应该在2之后找出一个大于2的元素代替“2”,可以找到的是3。这样,在“3”出现在“2”的位置后,“3”之后的元素应该进行“归零”,也就是需要进行升序排列。以上就是本算法的基本思想,以下给出cpp代码,以及相关测试如下:

#include<iostream>
#include<vector>

using namespace std;
// In array arr, if there is i < j, and arr[i] < arr[j], we can conclued that
// there is next permutation for arr.
// So we search from the end to front, and check that there is
// arr[i] > arr[i - 1]. If we get such i, we just swap arr[i - 1] with the
// first element in arr[i:end] which greater than arr[i - 1]. Otherwise we
// just reverse the arr as ther requirement of the question.
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int len = nums.size() - 1;
int pos = len;
int temp;
// Find the ajancent reverse element.
while (pos > 0 && nums[pos] <= nums[pos - 1]) {
pos --;
}
// If we find it, just swap it with the first element greater than it
// by searching from end to begin.
if (pos > 0) {
temp = nums[pos - 1];
int swap_pos = len;
for (; swap_pos >= pos; swap_pos --) {
if (nums[swap_pos] > nums[pos - 1]) {
break;
}
}
nums[pos - 1] = nums[swap_pos];
nums[swap_pos] = temp;
}
// Reverse the left element in ascend order.
for (int i = 0; i < (len - pos + 1) / 2; i ++) {
temp = nums[pos + i];
nums[pos + i] = nums[len - i];
nums[len - i] = temp;
}
}
};
int main(int argc, char* argv[]) {
Solution so;
vector<int> test;
test.push_back(1);
test.push_back(3);
test.push_back(2);
so.nextPermutation(test);
for (int i = 0; i < test.size(); i ++) {
cout<<test[i]<<" ";
}
cout<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode cpp