39. Combination Sum
Explanation
To solve this problem, we can use backtracking to generate all possible combinations of candidates that sum up to the target. We start with an empty combination and recursively explore all possibilities by either including or excluding each candidate in the current combination.
Algorithm
- Sort the candidates array to easily avoid duplicates in the final result.
- Define a recursive backtracking function that takes the current combination, current index in the candidates array, and remaining target as parameters.
- In the backtracking function:
- If the target becomes 0, add the current combination to the result.
- Iterate over the candidates starting from the current index.
- For each candidate:
- Add the candidate to the current combination.
- Recursively call the function with the updated combination, the same index (allowing duplicates), and the reduced target by subtracting the candidate value.
- Remove the candidate from the current combination to backtrack and try the next candidate.
- Call the backtracking function with an empty combination, starting from the first candidate, and the initial target.
- Return the list of unique combinations.
Time Complexity
The time complexity of this approach is O(2^N), where N is the number of candidates. This is because for each candidate, we have two choices - either include it or exclude it.
Space Complexity
The space complexity is O(N) to store the recursive call stack.
import java.util.*;
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(candidates);
backtrack(result, new ArrayList<>(), candidates, target, 0);
return result;
}
private void backtrack(List<List<Integer>> result, List<Integer> combination, int[] candidates, int target, int start) {
if (target == 0) {
result.add(new ArrayList<>(combination));
return;
}
for (int i = start; i < candidates.length; i++) {
if (candidates[i] > target) {
break;
}
combination.add(candidates[i]);
backtrack(result, combination, candidates, target - candidates[i], i);
combination.remove(combination.size() - 1);
}
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.