Leetcode Next Permutation
2015-10-23 12:11
519 查看
Leetcode Next Permutation ,通过查看排列的特性,可以发现,每一次改变值的位置之后的元素都是按升序排列的,如:arr = [5, 4, 2, 3, 1],可以知道其下一个排列为:brr = [5, 4, 3, 1, 2],对于arr可以发现元素“2”后面元素为降序排列,那么如果要生成下一个序列,就应该在2之后找出一个大于2的元素代替“2”,可以找到的是3。这样,在“3”出现在“2”的位置后,“3”之后的元素应该进行“归零”,也就是需要进行升序排列。以上就是本算法的基本思想,以下给出cpp代码,以及相关测试如下:
#include<iostream> #include<vector> using namespace std; // In array arr, if there is i < j, and arr[i] < arr[j], we can conclued that // there is next permutation for arr. // So we search from the end to front, and check that there is // arr[i] > arr[i - 1]. If we get such i, we just swap arr[i - 1] with the // first element in arr[i:end] which greater than arr[i - 1]. Otherwise we // just reverse the arr as ther requirement of the question. class Solution { public: void nextPermutation(vector<int>& nums) { int len = nums.size() - 1; int pos = len; int temp; // Find the ajancent reverse element. while (pos > 0 && nums[pos] <= nums[pos - 1]) { pos --; } // If we find it, just swap it with the first element greater than it // by searching from end to begin. if (pos > 0) { temp = nums[pos - 1]; int swap_pos = len; for (; swap_pos >= pos; swap_pos --) { if (nums[swap_pos] > nums[pos - 1]) { break; } } nums[pos - 1] = nums[swap_pos]; nums[swap_pos] = temp; } // Reverse the left element in ascend order. for (int i = 0; i < (len - pos + 1) / 2; i ++) { temp = nums[pos + i]; nums[pos + i] = nums[len - i]; nums[len - i] = temp; } } }; int main(int argc, char* argv[]) { Solution so; vector<int> test; test.push_back(1); test.push_back(3); test.push_back(2); so.nextPermutation(test); for (int i = 0; i < test.size(); i ++) { cout<<test[i]<<" "; } cout<<endl; return 0; }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- CPP 虚函数、虚函数表及虚拟继承(转)
- [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
- Deploying Control Plane Policing
- 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... 题解