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

SOLUTION 1:
還是經典的遞歸模板。需要處理的情況是:我們先把Num排序,然后只能連續地選,這樣就可以避免生成重復的solution.
例子:1 2 3 4 4 4 5 6 7 8
444這個的選法只能:4, 44, 444連續這三種選法
我們用一個visit的數組來記錄哪些是選過的。
1 public class Solution { 2 public List<List<Integer>> permuteUnique(int[] num) { 3 List<List<Integer>> ret = new ArrayList<List<Integer>>(); 4 if (num == null || num.length == 0) { 5 return ret; 6 } 7 8 // For deal with the duplicate solution, we should sort it. 9 Arrays.sort(num); 10 boolean[] visit = new boolean[num.length]; 11 12 dfs(num, new ArrayList<Integer>(), ret, visit); 13 14 return ret; 15 } 16 17 public void dfs(int[] num, ArrayList<Integer> path, List<List<Integer>> ret, boolean[] visit) { 18 int len = num.length; 19 if (path.size() == len) { 20 ret.add(new ArrayList<Integer>(path)); 21 return; 22 } 23 24 for (int i = 0; i < len; i++) { 25 // 只能連續地選,這樣就可以避免生成重復的solution. 26 // 例子:1 2 3 4 4 4 5 6 7 8 27 // 444這個的選法只能:4, 44, 444連續這三種選法 28 if (visit[i] || (i != 0 && visit[i - 1] && num[i] == num[i - 1])) { 29 continue; 30 } 31 32 // 遞歸以及回溯 33 visit[i] = true; 34 path.add(num[i]); 35 dfs(num, path, ret, visit); 36 path.remove(path.size() - 1); 37 visit[i] = false; 38 } 39 } 40 }
SOLUTION 2:
用一個pre來記錄選過的值,也可以達到同樣的目的,只取第一個可以取到的位置,后面再取也是一樣的解。用pre記下來,后面就不要再取同樣的值了
1 // SOLUTION 2: 2 // 使用一個pre來記錄。只取第一個可以取的位置 3 public void dfs(int[] num, ArrayList<Integer> path, List<List<Integer>> ret, boolean[] visit) { 4 int len = num.length; 5 if (path.size() == len) { 6 ret.add(new ArrayList<Integer>(path)); 7 return; 8 } 9 10 long pre = Long.MIN_VALUE; 11 for (int i = 0; i < len; i++) { 12 int n = num[i]; 13 // 只取第一個可取的位置,因為別的位置取到的也沒有區別 14 if (visit[i] || pre == n) { 15 continue; 16 } 17 pre = n; 18 19 // 遞歸以及回溯 20 visit[i] = true; 21 path.add(n); 22 dfs(num, path, ret, visit); 23 path.remove(path.size() - 1); 24 visit[i] = false; 25 } 26 }
GITHUB:
https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/permutation/PermuteUnique.java
