ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

组合总和(来源力扣)

2022-01-27 23:59:06  阅读:191  来源: 互联网

标签:index target 组合 backTrace 力扣 candidates ans 总和 combinate


给你一个 无重复元素 的整数数组 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]]

方法1:回溯

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> ans = new ArrayList<>();
        List<Integer> combinate = new ArrayList<>();
        backTrace(candidates, target, ans, combinate, 0);
        return ans;
    }
    private void backTrace(int[] candidates, int target, List<List<Integer>> ans, List<Integer> combinate, int index) {
        if(index == candidates.length)
            return;
        if(target == 0) {
            ans.add(new ArrayList<>(combinate));
            return;
        }
        backTrace(candidates, target, ans, combinate, index + 1);
        if(target - candidates[index] >= 0) {
            combinate.add(candidates[index]);
            backTrace(candidates, target - candidates[index], ans, combinate, index);
            combinate.remove(combinate.size() - 1);
        }
    } 
}

总结:遇到组合的问题,回溯是一个不错的想法,可以找出不重复的所有结果。此代码中 backTrace(candidates, target, ans, combinate, index + 1) 保证了可以跳到下一个数继续寻找;backTrace(candidates, target - candidates[index], ans, combinate, index) 可以保证每个数可以重复使用。同时也应该注意回溯中到达下一个情况后,仍需恢复到原来的状态。

标签:index,target,组合,backTrace,力扣,candidates,ans,总和,combinate
来源: https://blog.csdn.net/qq_53198408/article/details/122725295

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有