组合总和(Lc39)——排序+剪枝+回溯

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

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

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

示例 1:

复制代码
输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释:
2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7 。
仅有这两种组合。

示例 2:

复制代码
输入: candidates = [2,3,5], target = 8
输出: [[2,2,2,2],[2,3,3],[3,5]]

示例 3:

复制代码
输入: candidates = [2], target = 1
输出: []

提示:

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

问题简要描述:返回所有组合

细节阐述:

  1. dfs(i,s),表示从下标 i 开始搜索,且剩余目标值为 s

Java

java 复制代码
class Solution {
    List<List<Integer>> ans = new ArrayList<>();
    List<Integer> t = new ArrayList<>();
    int[] candidates;    
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        this.candidates = candidates;
        dfs(0, target);
        return ans;
    }

    void dfs(int i, int s) {
        if (s == 0) {
            ans.add(new ArrayList<>(t));
            return;
        }
        if (i >= candidates.length || s < candidates[i]) {
            return;
        }
        dfs(i + 1, s);
        t.add(candidates[i]);
        dfs(i, s - candidates[i]);
        t.remove(t.size() - 1);
    }    
}

Python3

python 复制代码
class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        def dfs(i: int, s: int):
            if s == 0:
                ans.append(t[:])
                return
            if i >= len(candidates) or s < candidates[i]:
                return
            dfs(i + 1, s)
            t.append(candidates[i])
            dfs(i, s - candidates[i])
            t.pop()

        candidates.sort()
        ans = []
        t = []
        dfs(0, target)
        return ans    

TypeScript

TypeScript 复制代码
function combinationSum(candidates: number[], target: number): number[][] {
    candidates.sort((a, b) => a - b);
    let ans = [];
    let t = [];
    const dfs = (i: number, s: number) => {
        if (s == 0) {
            ans.push(t.slice());
            return;
        }
        if (i >= candidates.length || s < candidates[i]) {
            return;
        }
        dfs(i + 1, s);
        t.push(candidates[i]);
        dfs(i, s - candidates[i]);
        t.pop();
    }
    dfs(0, target);
    return ans;  
};
相关推荐
徐子童12 分钟前
优选算法---链表
数据结构·算法·链表·面试题
如意.75913 分钟前
从零开始的指针(3)
算法
CYH&JK14 分钟前
数据结构---链式队列
数据结构
cwplh35 分钟前
MX模拟赛总结
算法·动态规划
浅川.251 小时前
xtuoj 随机数
算法
shan&cen1 小时前
Day02 集合 | 30. 串联所有单词的子串、146. LRU 缓存、811. 子域名访问计数
java·数据结构·算法·缓存
阿方.9181 小时前
《树与二叉树详解:概念、结构及应用》
数据结构·二叉树··知识分享
NAGNIP1 小时前
大模型微调框架之TRL
算法
麦当_1 小时前
SwipeMultiContainer 滑动切换容器算法指南
前端·javascript·算法
橘子132 小时前
递归,搜索与回溯算法
算法