|
| 1 | +package medium; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Arrays; |
| 5 | +import java.util.List; |
| 6 | + |
| 7 | +import utils.CommonUtils; |
| 8 | + |
| 9 | +public class PermutationsII { |
| 10 | + /**Looked at this post: https://discuss.leetcode.com/topic/31445/really-easy-java-solution-much-easier-than-the-solutions-with-very-high-vote*/ |
| 11 | + public List<List<Integer>> permuteUnique(int[] nums) { |
| 12 | + List<List<Integer>> result = new ArrayList(); |
| 13 | + if (nums == null || nums.length == 0) return result; |
| 14 | + boolean[] used = new boolean[nums.length]; |
| 15 | + List<Integer> list = new ArrayList(); |
| 16 | + Arrays.sort(nums); |
| 17 | + dfs(nums, used, list, result); |
| 18 | + return result; |
| 19 | + } |
| 20 | + |
| 21 | + |
| 22 | + private void dfs(int[] nums, boolean[] used, List<Integer> list, List<List<Integer>> result) { |
| 23 | + if (list.size() == nums.length){ |
| 24 | + result.add(new ArrayList(list)); |
| 25 | + return; |
| 26 | + } |
| 27 | + for (int i = 0; i < nums.length; i++){ |
| 28 | + if (used[i]) continue; |
| 29 | + if (i > 0 && nums[i - 1] == nums[i] && !used[i - 1]) |
| 30 | + continue; |
| 31 | + /** |
| 32 | + * For this line, both !used[i-1] and used[i-1] will AC. It is because the first one makes sure when |
| 33 | + * duplicates are selected, the order is ascending (index from small to large). However, |
| 34 | + * the second one means the descending order. |
| 35 | + */ |
| 36 | + used[i] = true; |
| 37 | + list.add(nums[i]); |
| 38 | + dfs(nums, used, list, result); |
| 39 | + used[i] = false; |
| 40 | + list.remove(list.size()-1); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + |
| 45 | + public static void main(String...args){ |
| 46 | + int[] nums = new int[]{1,1,2}; |
| 47 | + PermutationsII test = new PermutationsII(); |
| 48 | + List<List<Integer>> result = test.permuteUnique(nums); |
| 49 | + CommonUtils.printIntegerList(result); |
| 50 | + } |
| 51 | +} |
0 commit comments