LeetCode 31: Next Permutation
2015-10-23 16:04
267 查看
Next Permutation
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
解题思路
若把 n 个整数的所有全排列按升序排好序,则 nextPermutation 函数应返回当前排列在该升序下的下一个排列。对当前排列从后向前扫描,找到第一对为升序的相邻元素,记为 i 和 i+1:
如果不存在这样一对为升序的相邻元素,则当前排列为降序,按题意应返回升序的排列;
否则,对当前排列从后向前扫描,找到第一个大于 i 的元素 k,交换 i 和 k,然后对从 i+1 开始到结束的子序列反转,则此时得到的新排列就为下一个字典序排列。
代码如下:
class Solution { public: void nextPermutation(vector<int>& nums) { int size = nums.size(); if (size < 2) return; int i, k; // 从后向前找到第一对为升序的相邻元素,nums[i] < nums[i+1] for (i = size - 2; i >= 0; --i) { if (nums[i+1] > nums[i]) break; } // 存在这样一对为升序的相邻元素 if (i >= 0) { // 从后向前找到第一个大于 nums[i] 的元素 nums[k] for (k = size - 1; k > i; --k) { if (nums[k] > nums[i]) break; } swap(nums[i], nums[k]); // 交换 nums[i] 和 nums[k] 的值 } // 反转 reverse(nums.begin() + i + 1, nums.end()); } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解