码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Permutations II

时间:2015-06-03 00:49:01      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:

Well, have you solved the nextPermutation problem? If so and you have handled the cases of duplicates at that problem, your code can be used in this problem. The idea is fairly simple:

  1. sort nums in ascending order, add it to res;
  2. generate the next permutation of nums using nextPermutation(), and add it to res;
  3. repeat 2 until the next permutation of nums returns to the sorted condition in 1.

The code is as follows. For more about the idea of nextPermutation(), please visit this solution.

 1     bool nextPermutation(vector<int>& nums) {
 2         int k = -1;
 3         for (int i = nums.size() - 2; i >= 0; i--) {
 4             if (nums[i] < nums[i + 1]) {
 5                 k = i;
 6                 break;
 7             }
 8         }
 9         if (k == -1) {
10             sort(nums.begin(), nums.end());
11             return false;
12         }
13         int l = -1;
14         for (int i = nums.size() - 1; i > k; i--) {
15             if (nums[i] > nums[k]) {
16                 l = i;
17                 break;
18             }
19         }
20         swap(nums[k], nums[l]);
21         reverse(nums.begin() + k + 1, nums.end());
22         return true;
23     }
24     vector<vector<int>> permuteUnique(vector<int>& nums) {
25         vector<vector<int> > res;
26         sort(nums.begin(), nums.end());
27         res.push_back(nums);
28         while (nextPermutation(nums))
29             res.push_back(nums);
30         return res;
31     }

 

[LeetCode] Permutations II

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4547994.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!