TikTok OA 面试真题解析:Combination Sum 组合总和

21次阅读
没有评论

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.

Example 1:

Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Explanation: 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate, and 7 = 7. These are the only two combinations.

这道题要求从一组互不相同的候选数中,找出所有和为目标值的唯一组合,并且每个数字可以重复使用。标准解法是回溯 /DFS:先对候选数组排序,从当前位置开始枚举是否选当前数字,并在递归中继续保留当前下标以支持重复选择;当当前和等于 target 时记录答案,超过 target 就剪枝。由于组合需要去重且不考虑顺序,回溯过程中按下标递增搜索即可自然避免重复结果。

正文完
 0