[LeetCode] 062: Next Permutation
来源:互联网 发布:好看的网络自制剧 编辑:程序博客网 时间:2024/06/06 20:59
[Problem]
(1)从后往前i = n-1 ~ 1,查找num[i] > num[i-1]的第一个i,说明这个地方的位置为初始位置(num[i-1] < num[i]),下一个排列需要替换num[i-1],从后往前 j = n-1 ~ i,查找第一个比num[i-1]大的数,交换num[i-1]和num[j],并将num[i:end]重新排序。
(2)如果无法找到满足上述条件的i,说明整个排列为逆序排列,那么下一个排列即为正序排列,只需要对num进行sort就行。
[Solution]
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
[Analysis](1)从后往前i = n-1 ~ 1,查找num[i] > num[i-1]的第一个i,说明这个地方的位置为初始位置(num[i-1] < num[i]),下一个排列需要替换num[i-1],从后往前 j = n-1 ~ i,查找第一个比num[i-1]大的数,交换num[i-1]和num[j],并将num[i:end]重新排序。
(2)如果无法找到满足上述条件的i,说明整个排列为逆序排列,那么下一个排列即为正序排列,只需要对num进行sort就行。
[Solution]
class Solution {说明:版权所有,转载请注明出处。Coder007的博客
public:
/**
* swap num[i] and num[j]
*/
void swap(vector<int> &num, int i, int j){
int tmp = num[i];
num[i] = num[j];
num[j] = tmp;
}
/**
* sort num[i:end)
*/
void mySort(vector<int> &num, int i){
vector<int>::iterator it;
it = num.begin();
for(int k = 0; k < i; ++k){
it++;
}
sort(it, num.end());
}
/**
* next permutation
*/
void nextPermutation(vector<int> &num) {
// Note: The Solution object is instantiated only once and is reused by each test case.
bool done = false;
for(int i = num.size()-1; i > 0; --i){
if(num[i] > num[i-1]){
for(int j = num.size()-1; j > i-1; --j){
if(num[j] > num[i-1]){
// swap
swap(num, i-1, j);
// sort
mySort(num, i);
// break
done = true;
break;
}
}
break;
}
}
// the last permutation
if(!done){
sort(num.begin(), num.end());
}
}
};
阅读全文
0 0
- [LeetCode] 062: Next Permutation
- LeetCode: Next Permutation
- LeetCode Next Permutation
- LeetCode : Next Permutation
- [Leetcode] Next Permutation
- [LeetCode] Next Permutation
- [Leetcode] Next Permutation
- leetcode 88: Next Permutation
- [LeetCode]Next Permutation
- LeetCode-Next Permutation
- [leetcode]Next Permutation
- LeetCode - Next Permutation
- LeetCode 31: Next Permutation
- 【leetcode】Next Permutation
- LeetCode题解:Next Permutation
- 【LeetCode】Next Permutation
- [LeetCode] Next Permutation
- LeetCode Next Permutation
- [LeetCode] 059: Multiply Strings
- 2017沈阳网络赛 1001 HDU 6194 string string string(后缀自动机 出现k次的子串个数)
- 2704:寻找平面上的极大点(4.6算法之贪心)
- [LeetCode] 060: N-Queens
- [LeetCode] 061: N-Queens II
- [LeetCode] 062: Next Permutation
- ConcurrentHashMap实现原理
- [LeetCode] 063: Palindrome Number
- httpclient_get_post
- 【转】简介ajax
- [LeetCode] 064: Palindrome Partition
- [LeetCode] 065: Palindrome Partitioning II
- [LeetCode] 066: Partition List
- [LeetCode] 067: Pascal\'s Triangle