Simple Java Solution


  • 0
    Z
    import java.util.ArrayList;
    import java.util.HashSet;
    import java.util.List;
    import java.util.Set;
    
    public class Solution {
        public List<List<Integer>> permuteUnique(int[] nums) {
            List<List<Integer>> result = new ArrayList<>();
            if (nums == null || nums.length == 0) {
                return result;
            }
            perm(result, nums, 0, nums.length - 1);
            return result;
        }
    
        public void perm(List<List<Integer>> result, int[] nums, int start, int end) {
            Set<Integer> swapedNum = new HashSet<>();
            if (start >= end) {
                List<Integer> list = new ArrayList<>();
                for (int num : nums) {
                    list.add(num);
                }
                result.add(list);
            } else {
                for (int i = start; i <= end; i++) {
                    if (swapedNum.add(nums[i])) {
                        swap(nums, i, start);
                        perm(result, nums, start + 1, end);
                        swap(nums, i, start);
                    }
                }
            }
        }
    
    
        public void swap(int[] nums, int i, int j) {
            int tmp = nums[i];
            nums[i] = nums[j];
            nums[j] = tmp;
        }
    
     
    }
    

Log in to reply
 

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