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.
LeetCode
大意:有數組包含不重複的數字,數字可以重複使用,找出能組成target的所有組合
理解:使用回溯法,為了避免重複,對於每個元素採用/不採用的累進加法
candidates = [2,3,6,7], target = 7
[] -> [2] -> [2, 2] -> [2, 2, 2] -> [2, 2, 2, 2] / -> [2, 2, 2, 3] -> [2, 2, 2, 6]
[] -> [3] -> [3, 3] -> [3, 3, 3]
...
不回去加以前的元素
class Solution {
fun combinationSum(candidates: IntArray, target: Int): List<List<Int>> {
val res = mutableListOf<List<Int>>()
fun generateList(currentArr: MutableList<Int>, sum: Int, targetIndex: Int) {
if (sum > target || targetIndex >= candidates.size ) {
return
}
if (sum == target) {
res.add(currentArr.toList())
return
}
generateList(currentArr.toMutableList(), sum, targetIndex + 1)
currentArr.add(candidates[targetIndex])
generateList(currentArr.toMutableList(), sum + candidates[targetIndex], targetIndex)
}
generateList(mutableListOf<Int>(), 0, 0)
return res.toList()
}
}