4ms simple standard java solution(backtracking)


  • 0
    C
    public List<List<Integer>> permute(int[] nums) {
            ArrayList<List<Integer>> result = new ArrayList<List<Integer>>();
            helper(nums.length, result,new ArrayList<Integer>(), nums);
            return result;
        }
        public void helper(int len, ArrayList<List<Integer>> result, ArrayList<Integer> curr, int[] nums){
            for(int i=0; i<len;i++){
                if(!curr.contains(nums[i])) {//if curr already contains nums[i], skip
                    curr.add(nums[i]); //add nums[i] if curr does not contain it
                    if(curr.size() == len) result.add(new ArrayList<Integer>(curr)); //if curr is full(has size of the input array), put it into the result list
                    else helper(len, result, curr, nums); //otherwise call self
                    curr.remove(curr.size()-1); //backtracking
                }
            }
        }
    

  • 0
    T
    This post is deleted!

  • 0
    T

    whats a time complexity of this solution ??


Log in to reply
 

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