Java simple recursive solution


  • 0
    R
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        if(nums==null || nums.length==0){
            return new ArrayList<>();
        }
        permuteRecursive(nums, result, new ArrayList<Integer>(),new ArrayList<Integer>());
        return result;
    
    }
    private void permuteRecursive(int[] nums, List<List<Integer>> result, List<Integer> usedIndex, List<Integer> usedNums){
        if(usedIndex.size()==nums.length){
            List<Integer> temp = new ArrayList<>(usedNums);
            result.add(temp);
            return;
        }
        for(int index=0; index<nums.length; index++){
            if(!usedIndex.contains(index)){
                usedIndex.add(index);
                usedNums.add(nums[index]);
                permuteRecursive(nums, result, usedIndex,usedNums);
                usedIndex.remove(usedIndex.size()-1);
                usedNums.remove(usedNums.size()-1);
            }
        }
    }

Log in to reply
 

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