daily pastebin goal
60%
SHARE
TWEET

Untitled

a guest May 16th, 2018 102 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.util.ArrayList;
  2. import java.util.Arrays;
  3. import java.util.List;
  4. import java.util.Stack;
  5.  
  6. public class Solution {
  7.  
  8.     private List<List<Integer>> res = new ArrayList<>();
  9.     private boolean[] used;
  10.  
  11.     private void findPermuteUnique(int[] nums, int depth, Stack<Integer> stack) {
  12.  
  13.         // System.out.println(Arrays.toString(used));
  14.         if (depth == nums.length) {
  15.             res.add(new ArrayList<>(stack));
  16.             return;
  17.         }
  18.  
  19.  
  20.         for (int i = 0; i < nums.length; i++) {
  21.  
  22.             if (!used[i]) {
  23.                 // 相当于树被剪枝
  24.                 if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) {
  25.                     continue;
  26.                 }
  27.                 used[i] = true;
  28.                 stack.add(nums[i]);
  29.                 findPermuteUnique(nums, depth + 1, stack);
  30.                 stack.pop();
  31.                 used[i] = false;
  32.             }
  33.  
  34.         }
  35.     }
  36.  
  37.     public List<List<Integer>> permuteUnique(int[] nums) {
  38.         int len = nums.length;
  39.         if (len == 0) {
  40.             return res;
  41.         }
  42.         Arrays.sort(nums);
  43.         used = new boolean[len];
  44.         findPermuteUnique(nums, 0, new Stack<>());
  45.         return res;
  46.     }
  47.  
  48.     public static void main(String[] args) {
  49.         // write your code here
  50.  
  51.         int[] nums = {1, 1, 2};
  52.         Solution solution = new Solution();
  53.         List<List<Integer>> permuteUnique = solution.permuteUnique(nums);
  54.         System.out.println(permuteUnique);
  55.     }
  56. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top