An interactive visualization of the backtracking approach to find all combinations that sum to a target. Watch how pruning eliminates branches where the running sum exceeds the target.
Backtracking LeetCode 39 โ MediumGiven 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.
Example: Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3], [7]]
fun combinationSum(candidates: IntArray, target: Int): List<List<Int>> { val result = mutableListOf<List<Int>>() fun backtrack(start: Int, current: MutableList<Int>, remaining: Int) { // enter backtrack if (remaining == 0) { result.add(current.toList()) return } for (i in start until candidates.size) { if (candidates[i] > remaining) continue current.add(candidates[i]) backtrack(i, current, remaining - candidates[i]) current.removeAt(current.size - 1) } } // end backtrack backtrack(0, mutableListOf(), target) return result}
The Combination Sum problem is solved using backtracking, which systematically explores all possible combinations by making choices and undoing them (backtracking) when they don't lead to a solution.