[Leetcode] Permutations II

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!来判断了,可以先排一下序,当序列逆序时结束。

 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 };
原文地址:https://www.cnblogs.com/easonliu/p/3632487.html