47. Permutations II java solutions

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],
  [2,1,1]
]


 1 public class Solution {
 2     List<List<Integer>> ans = new ArrayList<List<Integer>>();
 3     public List<List<Integer>> permuteUnique(int[] nums) {
 4         List<Integer> list = new ArrayList<Integer>();
 5         boolean[] visit = new boolean[nums.length];
 6         Arrays.sort(nums);
 7         DFS(list,nums,visit);
 8         return ans;
 9     }
10     
11     public void DFS(List<Integer> list, int[] nums, boolean[] visit){
12         if(list.size() == nums.length){
13             ans.add(list);
14             return;
15         }
16         
17         for(int i = 0; i < nums.length; i++){
18             if(visit[i] || (i>0 && nums[i] == nums[i-1] && !visit[i-1])) continue;
19             visit[i] = true;
20             List<Integer> tmp = new ArrayList<>(list);
21             tmp.add(nums[i]);
22             DFS(tmp,nums,visit);
23             visit[i] = false;
24         }
25     }
26 }

 

46. Permutations java solutions

posted @ 2016-07-15 09:13  Miller1991  阅读(295)  评论(0编辑  收藏  举报