LC每日一题|20240420 - 39. 组合总和

3 阅读1分钟

LC每日一题|20240420 - 39. 组合总和

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 **不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。

candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。 

对于给定的输入,保证和为 target 的不同组合数少于 150 个。

提示:

  • 1 <= candidates.length <= 30
  • 2 <= candidates[i] <= 40
  • candidates 的所有元素 互不相同
  • 1 <= target <= 40

题目等级:Medium

解题思路

这题应该不用说太多,回溯的入门题~

AC代码

class Solution {
    val res = ArrayList<List<Int>>()
    val cur = ArrayList<Int>()
    fun combinationSum(candidates: IntArray, target: Int): List<List<Int>> {
        dfs(candidates, target, 0)
        return res
    }

    fun dfs(candidates: IntArray, target: Int, index: Int) {
        if (index == candidates.size) return 
        if (target == 0) {
            res.add(ArrayList<Int>(cur))
            return 
        }
        dfs(candidates, target, index + 1)
        if (target >= candidates[index]) {
            cur.add(candidates[index])
            dfs(candidates, target - candidates[index], index)
            cur.removeAt(cur.size - 1)
        }
    }
}

碎碎念

盲猜明天是 40. 组合总和 II