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].

 1         public static List<List<int>> PermutationsII(List<int> num)
 2         {
 3             List<List<int>> ret = new List<List<int>>();
 4 
 5             if (num.Count == 0)
 6                 return ret;
 7             if (num.Count == 1)
 8             {
 9                 ret.Add(num); 
10                 return ret;
11             }
12 
13             num.Sort();
14 
15             ret.Add(new List<int>(num));
16             while(NextPermutationII(num))
17                 ret.Add(new List<int>(num));
18             
19             return ret;
20         }
21 
22         public static bool NextPermutationII(List<int> num)
23         {
24             if (num.Count <= 1)
25                 return false;
26 
27             //find the falling edge
28             int edge = -1;
29             for (int i = num.Count - 2; i >= 0; i--)
30             {
31                 if (num[i] < num[i + 1])
32                 {
33                     edge = i;
34                     break;
35                 }
36             }
37 
38             if (edge > -1)
39             {
40                 //find replacement
41                 for (int i = edge + 1; i < num.Count; i++)
42                 {
43                     if (num[edge] >= num[i])
44                     {
45                         NextPermutationSwap(num, edge, i - 1);
46                         break;
47                     }
48                     if (i == num.Count - 1)
49                     {
50                         NextPermutationSwap(num, edge, i);
51                         break;
52                     }
53                 }
54             }
55             else
56             {
57                 return false;
58             }
59 
60             for (int i = edge + 1, j = num.Count - 1; i <= edge + (num.Count - edge - 1) / 2; i++, j--)
61             {
62                 NextPermutationSwap(num, i, j);
63             }
64             return true;
65         }

代码分析:

  先把输入数组排列一下,利用之前做的一题,找下一个permutation的那一题,改写一下函数,如果找到返回true,然后再加入到结果里面。

 

相关文章:

  • 2021-12-28
  • 2021-05-22
  • 2021-06-04
  • 2022-02-16
  • 2021-05-22
  • 2021-09-08
  • 2021-10-14
  • 2022-12-23
猜你喜欢
  • 2021-06-07
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案