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.
LeetCode-39: 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 problem can be solved using a backtracking approach. The key idea is to explore all possible combinations of the given numbers that sum up to the target.
Once we have a valid combination, we can add it to the result list. After every recursive call, we backtrack to explore other possible combinations.
Here is a high-level overview of the approach:
Here is a Java implementation of the above approach:
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> currentGroup = new ArrayList<>();
solve(candidates, target, result, currentGroup ,0);
return result;
}
private void solve(int[] candidates,
int remaining,
List<List<Integer>> result,
List<Integer> currentGroup,
int index){
// if the remaining target is 0, i.e. we have found a valid combination
// add the current combination to the result
if(remaining == 0){
result.add(new ArrayList<>(currentGroup));
return;
}
// if the remaining target is less than 0,
// we have exceeded the target, so return
if(remaining < 0){
return;
}
for(int i=index; i < candidates.length; i++){
// consider the current candidate
currentGroup.add(candidates[i]);
// recursively call the function with the updated
// combination, remaining target, and the current index
solve(candidates, remaining - candidates[i], result, currentGroup , i);
// backtrack by removing the last element
currentGroup.remove(currentGroup.size() - 1);
}
}
The time complexity for this approach is $O(N^T)$, where $N$ is the number of candidates and $T$ is the target sum. This is because for each candidate, we have two choices:
Be notified of new posts. Subscribe to the RSS feed.