Using HashSet and two swaps


  • 0
    A
    public class Solution {
        public List<List<Integer>> permuteUnique(int[] nums) {
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            List<Integer> list = new ArrayList<Integer>();
            if (nums == null || nums.length == 0) {
                return res;
            }
            helper(nums, 0, list, res);
            return res;
        }
        private void helper(int[] nums, int index, List<Integer>list, List<List<Integer>> res) {
            if (index == nums.length) {
                res.add(new ArrayList<Integer>(list));
                return;
            }
            Set<Integer> set = new HashSet<Integer>();
            for (int i = index; i < nums.length; i ++) {
                if (!set.contains(nums[i])) {
                    set.add(nums[i]);
                    list.add(nums[i]);
                    swap(i, index, nums);
                    
                    helper(nums, index + 1, list, res);
                    list.remove(list.size() - 1);
                    swap(i, index, nums);
                }
            }
        }
        private void swap(int left, int right, int[] array) {
            int tmp = array[left];
            array[left] = array[right];
            array[right] = tmp;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.