|
| 1 | +//LeetCode 47. Permutations II |
| 2 | +//Question - https://leetcode.com/problems/permutations-ii/ |
| 3 | + |
| 4 | +class Solution { |
| 5 | + public List<List<Integer>> permuteUnique(int[] nums) { |
| 6 | + List<List<Integer>> res = new ArrayList<>(); |
| 7 | + Arrays.sort(nums); |
| 8 | + boolean visit[] = new boolean[nums.length]; |
| 9 | + |
| 10 | + helper(nums, visit, new ArrayList<>(), res); |
| 11 | + return res; |
| 12 | + } |
| 13 | + |
| 14 | + public void helper(int nums[], boolean visit[], List<Integer> perm, List<List<Integer>> res){ |
| 15 | + //Base Case |
| 16 | + if(perm.size() == nums.length){ |
| 17 | + res.add(new ArrayList<>(perm)); |
| 18 | + return; |
| 19 | + } |
| 20 | + |
| 21 | + for(int i = 0 ; i < nums.length ; i++){ |
| 22 | + //Check if nums[i] is already in the current permutation or not |
| 23 | + //The 2nd check is for duplicates |
| 24 | + |
| 25 | + /* |
| 26 | + Generating repeated permutations from duplicates can be avoided by using two |
| 27 | + different conditions - |
| 28 | + 1. (i > 0 && nums[i] == nums[i-1] && visit[i-1]) continue; |
| 29 | + This means include current number if the previous identical number is not |
| 30 | + included. After tracing out the state space tree, we can see that this condition |
| 31 | + creates the permutation by the last duplicate number, any permutation with an |
| 32 | + intermediate identical number would never reach the base case and creates a |
| 33 | + waste of space and time. |
| 34 | + |
| 35 | + 2. (i > 0 && nums[i] == nums[i-1] && !visit[i-1]) continue; |
| 36 | + This means that include current number if the previous identical number is |
| 37 | + included. After tracing out the state space tree, we can see that this condition |
| 38 | + creates the permutation by the first duplicate number, any permutation with an |
| 39 | + intermediate identical number is stopped from going deeper into recursion, |
| 40 | + saving time and space. |
| 41 | + */ |
| 42 | + if(visit[i] || (i > 0 && nums[i] == nums[i-1] && !visit[i-1])) continue; |
| 43 | + |
| 44 | + //mark nums[i] as visited for the current permutation |
| 45 | + visit[i] = true; |
| 46 | + perm.add(nums[i]); |
| 47 | + |
| 48 | + //generate the permutation further |
| 49 | + helper(nums, visit, perm, res); |
| 50 | + |
| 51 | + //backtrack to generate new permutation |
| 52 | + visit[i] = false; |
| 53 | + perm.remove(perm.size()-1); |
| 54 | + } |
| 55 | + } |
| 56 | +} |
0 commit comments