Next Permutation
2016-04-19 23:17
375 查看
题目大意:
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) 对于任何数列,从右往左看,要想改变的一定是找那种递增着突然递减的那个值。 如:1,2,5,3,1. 那么要改变的值一定是2。因为2的右边的这个序列值已经是最大的了。
2) 将这个值2存下来 temp=2,然后对于2,5,3,1的这一段进行从小到大排序,得到1,2,3,5。
3) 对这个序列进行从尾到头遍历,若找到与temp一样的值,则将比2大的数3存入temp, 然后将3的位置开始到头的位置往后移动一位,最后将temp的值存入第一位,即可得到
3,1,2,5。
我的代码:
void nextPermutation(vector<int>& nums) {
int len = nums.size();
if(len < 2) return;
vector<int>:: iterator it = nums.begin();
int i = len-1;
for(; i>= 1; i--){
if(nums[i] <= nums[i-1])
continue;
else
break;
}
if(i == 0)
sort(it,nums.end());
else{
int temp = nums[i-1];
sort((it+i-1),nums.end());
int k = len-1;
for(; k >= i-1; k--){
if(nums[k]==temp){
temp = nums[k+1];
break;
}
}
for(int p = k; p >= i-1;p--){
nums[p+1] = nums[p];
}
nums[i-1] = temp;
}
return;
}
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
题目意思:就是给定一组数据,找到这组数据按照字典排列的下一个比它大的数列。其中数列的值的递增是从右到左。若这个数列已经是最大的了,则将它变为它最小值的排列。
我的思路:
1) 对于任何数列,从右往左看,要想改变的一定是找那种递增着突然递减的那个值。 如:1,2,5,3,1. 那么要改变的值一定是2。因为2的右边的这个序列值已经是最大的了。
2) 将这个值2存下来 temp=2,然后对于2,5,3,1的这一段进行从小到大排序,得到1,2,3,5。
3) 对这个序列进行从尾到头遍历,若找到与temp一样的值,则将比2大的数3存入temp, 然后将3的位置开始到头的位置往后移动一位,最后将temp的值存入第一位,即可得到
3,1,2,5。
我的代码:
void nextPermutation(vector<int>& nums) {
int len = nums.size();
if(len < 2) return;
vector<int>:: iterator it = nums.begin();
int i = len-1;
for(; i>= 1; i--){
if(nums[i] <= nums[i-1])
continue;
else
break;
}
if(i == 0)
sort(it,nums.end());
else{
int temp = nums[i-1];
sort((it+i-1),nums.end());
int k = len-1;
for(; k >= i-1; k--){
if(nums[k]==temp){
temp = nums[k+1];
break;
}
}
for(int p = k; p >= i-1;p--){
nums[p+1] = nums[p];
}
nums[i-1] = temp;
}
return;
}
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- 解析从源码分析常见的基于Array的数据结构动态扩容机制的详解
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解