sweet1cris

Untitled

Jan 9th, 2018
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.96 KB | None | 0 0
  1. class Solution {
  2.     /**
  3.      * @param nums: A list of integers.
  4.      * @return: A list of unique permutations.
  5.      */
  6.     public List<List<Integer>> permuteUnique(int[] nums) {
  7.    
  8.         ArrayList<List<Integer>> results = new ArrayList<List<Integer>>();
  9.    
  10.         if (nums == null) {
  11.             return results;
  12.         }
  13.    
  14.         if(nums.length == 0) {
  15.             results.add(new ArrayList<Integer>());
  16.             return results;
  17.         }
  18.  
  19.         Arrays.sort(nums);
  20.         ArrayList<Integer> list = new ArrayList<Integer>();
  21.         int[] visited = new int[nums.length];
  22.         for ( int i = 0; i < visited.length; i++){
  23.             visited[i] = 0;
  24.         }
  25.      
  26.         helper(results, list, visited, nums);    
  27.         return results;
  28.     }
  29.    
  30.    
  31.     public void helper(ArrayList<List<Integer>> results,
  32.                    ArrayList<Integer> list, int[] visited, int[] nums) {
  33.        
  34.         if(list.size() == nums.length) {
  35.             results.add(new ArrayList<Integer>(list));
  36.             return;
  37.         }
  38.        
  39.         for(int i = 0; i < nums.length; i++) {
  40.             if ( visited[i] == 1 || ( i != 0 && nums[i] == nums[i - 1]
  41.             && visited[i-1] == 0)){
  42.                 continue;
  43.             }
  44.             /*
  45.             上面的判断主要是为了去除重复元素影响。
  46.             比如,给出一个排好序的数组,[1,2,2],那么第一个2和第二2如果在结果中互换位置,
  47.             我们也认为是同一种方案,所以我们强制要求相同的数字,原来排在前面的,在结果
  48.             当中也应该排在前面,这样就保证了唯一性。所以当前面的2还没有使用的时候,就
  49.             不应该让后面的2使用。
  50.             */
  51.             visited[i] = 1;
  52.             list.add(nums[i]);
  53.             helper(results, list, visited, nums);
  54.             list.remove(list.size() - 1);
  55.             visited[i] = 0;
  56.         }
  57.      }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment