LeetCode-Next Permutation
2014-08-17 14:48
89 查看
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.
Solution:
Code:
<span style="font-size:14px;">class Solution {
public:
void nextPermutation(vector<int> &num) {
const int length = num.size();
int index = length-1;
for (; index >= 1; --index)
if (num[index-1] < num[index])
break;
if (index == 0) {
sort(num.begin(), num.end());
return;
}
int begin = index;
int small = index-1;
index = length-1;
for (; index >= 0; --index)
if (num[index] > num[small])
break;
swap(num[small], num[index]);
sort(num.begin()+begin, num.end());
}
};</span>
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
Solution:
Code:
<span style="font-size:14px;">class Solution {
public:
void nextPermutation(vector<int> &num) {
const int length = num.size();
int index = length-1;
for (; index >= 1; --index)
if (num[index-1] < num[index])
break;
if (index == 0) {
sort(num.begin(), num.end());
return;
}
int begin = index;
int small = index-1;
index = length-1;
for (; index >= 0; --index)
if (num[index] > num[small])
break;
swap(num[small], num[index]);
sort(num.begin()+begin, num.end());
}
};</span>
相关文章推荐
- LeetCode-Triangle
- LeetCode | Max Points on a Line
- LeetCode: Combination Sum II [039]
- LeetCode-Single Number II
- [Leetcode] Combination Sum II
- [LeetCode]96.Unique Binary Search Trees
- [LeetCode] N-Queens
- Binary Tree Zigzag Level Order Traversal——LeetCode
- Leetcode[4]-Median of Two Sorted Arrays
- leetcode 064 —— Minimum Path Sum
- Leetcode: Combination Sum
- <LeetCode OJ> 67. Add Binary
- 积跬步至千里系列之十一--leetcode小结
- LeetCode *** 27. Remove Element
- Leetcode 83. Remove Duplicates from Sorted List
- LeetCode 题目总结/分类
- Leetcode3:Longest Substring Without Repeating Characters
- LeetCode169. Majority Element C语言
- 个人记录-LeetCode 64. Minimum Path Sum
- leetcode 278. First Bad Version