给定一个由不同整数构成的数组 nums 和一个整数 target ,请你从 nums 找出总和是 target 的组合的个数。解集中可以重复使用 nums 中的元素。且解集中数字顺序不同视为不同的组合。
数据范围: 数组长度满足 ,数组中的数满足 ,
[1,2,3],4
7
所有可能的组合为: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1)
[9],10
0
[9],18
1
[[9,9]]
function combination( nums , target ) { // write code here const res = [] const fn = (i, path) => { path.push(i) let sum = path.reduce((s, val) => s += val, 0) if (sum > target) { return } if (sum == target) { res.push([...path]) return } for (let j = 0; j < nums.length; j++) { fn(nums[j], path) // 回溯 path.pop() } } for (let i = 0; i < nums.length; i++) { fn(nums[i], []) } return res.length }