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

 1 public class Solution {
 2      public List<List<Integer>> permuteUnique(int[] num) {
 3          List<List<Integer>> result = new ArrayList<List<Integer>>();
 4          List<Integer> curr = new ArrayList<Integer>();
 5          Arrays.sort(num);
 6          dfs(result, curr, num, 0);
 7          return result;
 8      }
 9 
10      void dfs(List<List<Integer>> result, List<Integer> curr, int[] num, int index) {
11          if (index == num.length) {
12              if (!result.contains(curr)) {
13                 result.add(new ArrayList<Integer>(curr));
14 
15              }
16          } else {
17              for (int i = index; i <num.length ; i++) {
18                  if (noSwap(num,i,index)) {
19                      continue;
20                  } else {
21                      swap(num, i, index);
22                  }
23                  curr.add(num[index]);
24                  dfs(result, curr, num, index + 1);
25                  curr.remove(curr.size() - 1);
26                  swap(num, index,i );
27 
28              }
29 
30          }
31      }
32 
33      void swap(int[] num, int indexA, int indexB) {
34          int temp = num[indexA];
35          num[indexA] = num[indexB];
36          num[indexB] = temp;
37      }
38 
39      boolean noSwap(int[] num, int i, int j) {
40          for (int k = j; k < i; k++) {
41              if (num[k] == num[i]) {
42                  return true;
43              }
44          }
45          return false;
46      }
47 
48 }

 

posted @ 2015-02-08 23:31  birdhack  阅读(113)  评论(0编辑  收藏  举报