• LeetCode220805_71、组合总和


    给你一个 无重复元素 的整数数组 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 。
    仅有这两种组合。

    来源:力扣(LeetCode)
    链接:https://leetcode.cn/problems/combination-sum
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    题解、回溯算法,注意每次可以选择重复元素,但是需要保证不是来回重复, 所以按照一定顺序遍历搜索,不重不漏。

    1. class Solution{
    2. public List<List<Integer>> combinationSum(int[] candidates, int target){
    3. List<List<Integer>> res = new ArrayList<>();
    4. Deque<Integer> path = new ArrayDeque<>();
    5. int len = candidates.length;
    6. dfs(candidates, 0, len, target, path, res);
    7. return res;
    8. }
    9. public void dfs(int[] candidates, int begin, int len, int target, Deque<Integer> path, List<List<Integer>> res){
    10. if(target < 0) return;
    11. if(target == 0){
    12. res.add(new ArrayList<>(path));
    13. return;
    14. }
    15. for(int i = begin; i < len; i++){
    16. path.addLast(candidates[i]);
    17. dfs(candidates, i, len, target - candidates[i], path, res);
    18. path.removeLast();
    19. }
    20. }
    21. }

    排序后可剪枝,前面数据相加后被target做差,已小于0,后面更小于,所以可直接退出for循环。

    1. class Solution{
    2. public List<List<Integer>> combinationSum(int[] candidates, int target){
    3. List<List<Integer>> res = new ArrayList<>();
    4. Deque<Integer> path = new ArrayDeque<>();
    5. int len = candidates.length;
    6. Arrays.sort(candidates);
    7. dfs(candidates, 0, len, target, path, res);
    8. return res;
    9. }
    10. public void dfs(int[] candidates, int begin, int len, int target, Deque<Integer> path, List<List<Integer>> res){
    11. if(target == 0){
    12. res.add(new ArrayList<>(path));
    13. }
    14. for(int i = begin; i < len; i++){
    15. if((target - candidates[i]) < 0 ){
    16. break;
    17. }
    18. path.addLast(candidates[i]);
    19. dfs(candidates, i, len, target - candidates[i], path, res);
    20. path.removeLast();
    21. }
    22. }
    23. }

  • 相关阅读:
    MFC使用MScomm32.ocx控件实现串口通信
    HTML CSS JS 通过键盘上下左右移动球体
    Spring Data JPA - Web 支持、使用Pageable 参数Thymeleaf 视图进行搜索/过滤、排序和分页
    谁拥有穿越周期的眼光?
    【imessage苹果群发位置推相册推】CloudKit API或通过作为程序一部分提供的CloudKit仪表板
    无法在 DLL“SQLite.Interop.dll”中找到名为”sIb4c632894b76cc1d“
    [架构设计] 创建型模型
    花几分钟整点jmeter花活,轻松超越90%软件测试
    实战攻防演练-Linux写入ssh密钥,利用密钥登录
    Ubuntu20.04配置CUDA+CUDNN深度学习环境
  • 原文地址:https://blog.csdn.net/Zoro_666/article/details/126186211