Java recursion 13ms


  • 0
    I
    public class Solution {
        public List<List<Integer>> permuteUnique(int[] nums) {
            Arrays.sort(nums);
            
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            List<Integer> cand = new ArrayList<Integer>();
            boolean[] taken = new boolean[nums.length];
            permute(res, taken, 0, nums, cand);
            
            return res;
        }
        
        void permute(List<List<Integer>> res, boolean[] taken, int pos, int[] nums, List<Integer> cand) {
            if(pos == nums.length) {
                res.add(new ArrayList<Integer>(cand));
                return;
            }
            
            for(int i = 0; i < nums.length; i++) {
                if(taken[i]) {
                    continue;
                }
                
                cand.add(nums[i]);
                taken[i] = true;
                permute(res, taken, pos + 1, nums, cand);
                taken[i] = false;
                cand.remove(cand.size() - 1);
                
                while(i + 1 < nums.length && nums[i] == nums[i + 1]) {
                    i++;
                }
            }
        }
        
    }
    

Log in to reply
 

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