works fine on smaller sets, but fails a big input with TLE


  • 0
    R
    public class Solution {
        public List<List<Integer>> threeSum(int[] nums) {
            if(nums.length==0) {
                return new ArrayList();
            }
            Arrays.sort(nums);
            List<List<Integer>> list = new ArrayList<>();
            return back(nums, 0, list, new ArrayList<>());
        }
        
        private static List<List<Integer>> back(int[] nums, int start, List<List<Integer>> list, List<Integer> temp) {
            // make sure that the sum is 0 & temp.size() == 3, then you can add it to the list
            if(temp.size()>3) {
                return list;
            } else if(temp.size()==3 && checksum(temp)==0) {
                Collections.sort(temp);
                if(!list.contains(temp)){
                    list.add(new ArrayList<>(temp));
                }
                return list;
            }
            for(int i=start; i<nums.length; i++) { // start==0
                temp.add(nums[i]);
                back(nums, i+1, list, temp);
                temp.remove(temp.size()-1);
            }
            return list;
        }
    
        private static int checksum(List<Integer> temp) {
            int sum = 0;
            for(int i : temp) {
                sum = sum+i;
            }
            return sum;
        }
    }
    

Log in to reply
 

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