首页 > 其他 > 详细

[Leetcode] Permutations II

时间:2014-03-29 16:34:28      阅读:440      评论:0      收藏:0      [点我收藏+]

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,
[1,1,2] have the following unique permutations:
[1,1,2][1,2,1], and [2,1,1].

 

注意不能用n!来判断了,可以先排一下序,当序列逆序时结束。

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

[Leetcode] Permutations II,布布扣,bubuko.com

[Leetcode] Permutations II

原文:http://www.cnblogs.com/easonliu/p/3632487.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!