Java efficient recursion beats 90 %


  • 0
    S
    class Solution {
        List<List<Integer>> result = new ArrayList<>();
        
        public List<List<Integer>> permute(int[] nums) {
            permute(new ArrayList<>(), nums, new boolean[nums.length]);
            return result;
        }
        
        private void permute(List<Integer> list, int[] nums, boolean[] used) {
            if(list.size() == nums.length) {
                result.add(new ArrayList<>(list));
                return;
            }
            
            for(int i=0; i<nums.length; i++) {
                if(used[i]) continue;
                list.add(nums[i]);
                used[i] = true;
                permute(list, nums, used);
                used[i] = false;
                list.remove(list.size()-1);
            }
            
        }
    }
    

    This solution doesn't use contains to check the nums array everytime a new element is inserted.


Log in to reply
 

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