5ms Java recursive solution, very clean


  • 1
    public class Solution {
        public List<List<Integer>> permute(int[] nums) {
            List<List<Integer>> result = new ArrayList<List<Integer>>();
            List<Integer> re = new ArrayList<>();
            
            // Error checking
            if(nums.length==0) return result;
            
            Arrays.sort(nums);
            helper(nums, nums.length, result, re);
            return result;
        }
        
        public void helper(int[] nums, int left, List<List<Integer>> result, List<Integer> re){
            if(left==0){
                List<Integer> r = new ArrayList<>(re);
                result.add(r);
                return;
            }
            
            for(int i=0; i<nums.length; i++){
                if(re.contains(nums[i])) continue;
                re.add(nums[i]);
                helper(nums, left-1, result, re);
                re.remove(re.size()-1);
            }
        } }

Log in to reply
 

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