share my concise solution


  • 0
    S
    public class Solution {
        public List<List<Integer>> permuteUnique(int[] nums) {
            List<List<Integer>> res = new ArrayList<>();
            helper(nums, 0, res);
            return res;
        }
        private void helper(int[] nums, int index, List<List<Integer>> res) {
            if (index == nums.length) {
                List<Integer> cur = new ArrayList<>();
                for (int i : nums) {
                    cur.add(i);
                }
                res.add(cur);
            }
            Set<Integer> set = new HashSet<>();
            for (int i = index; i < nums.length; i++) {
                if (set.add(nums[i])) {
                    swap(nums, i, index);
                    helper(nums, index + 1, res);
                    swap(nums, i, index);
                }
            }
        }
        private void swap(int[] nums, int left, int right) {
            int tmp = nums[left];
            nums[left] = nums[right];
            nums[right] = tmp;
        }
    }
    
    

Log in to reply
 

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