This is my approach to the problem. I didn’t use recursion or backtracking like we are supposed to but did it iteratively and got a time limit exceeded error. I think my solution is correct despite being very convoluted and lengthy. Could someone help me refine it and slightly correct any mistakes I may be overlooking? I’m not looking for an entirely different solution using recursion but only tweaks to my current one so that it passes all testcases.
https://leetcode.com/problems/combination-sum/description/
Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.
The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the
frequency of at least one of the chosen numbers is different.
The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input.
Example 1:
Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Explanation:
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.
Example 2:
Input: candidates = [2,3,5], target = 8
Output: [[2,2,2,2],[2,3,3],[3,5]]
Example 3:
Input: candidates = [2], target = 1
Output: []
class Solution {
public List<List> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
int sum = 0;
ArrayList<Integer> list = new ArrayList<>();
List<List<Integer>> finalL = new ArrayList<>();
for(int i = 0; i< candidates.length; i++) {
boolean circ = true;
int temp = 2*candidates[i];
sum = 0;
boolean b = true;
int j;
j = i;
while(b==true) {
if(sum>= target) {
if(sum==target) {
finalL.add(list);
}
if(j== candidates.length-1) {
circ = true;
int x;
x = list.get(list.size()-1);
for(int k = 0; k< candidates.length; k++) {
if(x == candidates[j]) {
j = k+1;
}
}
}
else{j = j+1;
circ = false;}
temp = list.get(list.size()-1) + list.get(list.size()-1);
list.remove(list.size() - 1);
list.remove(list.size() - 1);
sum = 0;
for (int num : list) {
sum += num;
}
while(sum< target) {
if(circ==true) {
sum = sum + candidates[j];
list.add(candidates[j]);
}
else if(candidates[j]< temp) {
if(j== candidates.length-1) {
b = false;
break;
}
j++;
}
else if(candidates[j]>=temp) {
sum = sum + candidates[j];
list.add(candidates[j]);}
}
}
}
}
return finalL;
}
}