LeetCode 31. Next Permutation
2016-11-03 18:18
423 查看
题目描述
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
解题思路
从后面开始向前找,找到第一个不是升序排列的,然后倒置那两个数字的之间的子串。
实现代码
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
解题思路
从后面开始向前找,找到第一个不是升序排列的,然后倒置那两个数字的之间的子串。
实现代码
class Solution { public: void nextPermutation(vector<int>& num) { if (num.size() < 2) return; int i, k; for (i = num.size() - 2; i >= 0; --i) if (num[i] < num[i + 1]) break; if (i < 0) { reverse(num.begin() , num.end()); return; } for (k = num.size() - 1; i >= 0 && k > i ; --k) if (num[i] < num[k]) break; if (i >= 0) { swap(num[i], num[k]); reverse(num.begin() + i + 1, num.end()); return; } } };
相关文章推荐
- Leetcode: 31. Next Permutation
- leetcode_middle_31_337. House Robber III
- [leetcode] 31.Next Permutation
- LeetCode 31 Next Permutation 寻找一个数字序列的比他大的最小序列
- LeetCode31. Next Permutation最清晰的解法
- Leetcode题解(31)
- [leetcode] 31. Next Permutation
- [leetcode 31] Next Permutation
- [Leetcode 31, medium] Next Permutation
- LeetCode-31-Next Permutation 贪心,排序
- LeetCode - 31. Next Permutation
- Leetcode 31. Next Permutation (Medium) (cpp)
- LeetCode (31) Divide two integers (不使用 *, /, mod 求两个数相除结果)
- LeetCode 31 Next Permutation(下一个排列)
- leetcode 31. Next Permutation
- leetcode 31 - next permutation
- Leetcode 31. Next Permutation
- leetcode 题解代码整理 31-35题
- leetcode 31. Next Permutation
- Leetcode-31. Next Permutation