0

I was practicing backtracking problems and started off with the Combination Sum problem in Leetcode 39. I worked on my own solution after watching a few YouTube videos to understand the problem better since my solution was failing even though I felt that the logic was right. (Basically I wasn't handling the case to remove redundant solutions, i.e. I had a solution that would get the Permutation of the solution but not the Combination!!

I wrote my code in java, I honestly didn't find many java solutions to this. Python solutions seemed pretty simple though. Maybe it's not the best space and time. I'll try to optimize it and post the update here.

I'm struggling to calculate the time and space complexity for this problem. I'm pretty weak at calculating the time and space usually and with this problem particularly, it's really confusing considering each element can be used multiple times and hence will be part of multiple solutions with multiple counts. I'm trying to calculate space since I use recursion and I'm using the tree method to check the stack size. But if anyone has a good approach to calculate time and space to such problems will be really helpful.

My code below. Any inputs to optimize it will be helpful!

class Solution {

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> mainList = new ArrayList<>();
        List<Integer> currList = new ArrayList<>();
        compute(0, currList, target, candidates, 0, mainList);
        return mainList;
    }

    void compute(int currSum, List<Integer> currList, int target, int[] candidates, int pos, List<List<Integer>> mainList){
        if(currSum > target || pos>(candidates.length-1)){
            return;
        }
        if(currSum == target){
            mainList.add(new ArrayList<>(currList));
            return;
        }
        currList.add(candidates[pos]);
        currSum = currSum+candidates[pos];
        compute(currSum, currList, target, candidates, pos, mainList);
        currSum = currSum-(currList.get(currList.size()-1));
        currList.remove(currList.size()-1);
        compute(currSum, currList, target, candidates, pos+1, mainList);
    }
}

I think one way is to sort the candidates array and if sum>target for position i we need not call the function for position i + 1.

nice_dev
  • 17,053
  • 2
  • 21
  • 35
Aditya
  • 33
  • 6

0 Answers0