Advertisement
Guest User

Untitled

a guest
Apr 18th, 2015
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. public class Solution {
  2. public List<List<Integer>> permuteUnique(int[] num) {
  3. List<List<Integer>> res = new ArrayList<>();
  4. if (num.length==0) return res;
  5. Arrays.sort(num); //sort so that duplicate numbers come together
  6. boolean[] visited = new boolean[num.length];
  7. List<Integer> ans = new ArrayList<>();
  8. helper(num,visited,ans,res);
  9. return res;
  10.  
  11. }
  12.  
  13. public void helper(int[] num, boolean[] visited, List<Integer> ans, List<List<Integer>> res){
  14. if (ans.size()==num.length){
  15. res.add(new ArrayList(ans));
  16. return;
  17. }
  18.  
  19. for(int i=0;i<num.length;i++){
  20. if (!visited[i]){
  21. visited[i]=true;
  22. ans.add(num[i]);
  23. helper(num,visited,ans,res);
  24. visited[i]=false;
  25. ans.remove(ans.size()-1);
  26. //back track. take care of the dups.
  27. while(i<num.length&&num[i]==num[i+1]) i++;//note that i will be incremented in the for loop, so it refers to the non duplicate element;
  28. }
  29. }
  30. }
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement