LeetCode 40. 组合总和 II(排列组合 回溯)
发布日期:2021-07-01 03:15:46 浏览次数:2 分类:技术文章

本文共 1382 字,大约阅读时间需要 4 分钟。

1. 题目

给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用一次

说明:

所有数字(包括目标数)都是正整数。
解集不能包含重复的组合

示例 1:输入: candidates = [10,1,2,7,6,1,5], target = 8,所求解集为:[  [1, 7],  [1, 2, 5],  [2, 6],  [1, 1, 6]]示例 2:输入: candidates = [2,5,2,1,2], target = 5,所求解集为:[  [1,2,2],  [5]]

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/combination-sum-ii

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

  • 类似题目

2. 回溯求解

class Solution {
public: vector
> combinationSum2(vector
& candidates, int target) {
sort(candidates.begin(), candidates.end()); vector
> ans; vector
subset; bt(0,0,target,subset,ans,candidates); return ans; } void bt(int i, int sum, int &target, vector
&subset, vector
> &ans, vector
&candidates) { if(i > candidates.size() || sum > target) return; if(i <= candidates.size() && sum == target) { ans.push_back(subset); return; } for(int j = i; j < candidates.size(); j++) { if(j > i && candidates[j-1] == candidates[j]) continue; subset.push_back(candidates[j]); bt(j+1, sum+candidates[j], target, subset, ans, candidates); subset.pop_back(); } }};

8 ms 7.1 MB


我的CSDN

长按或扫码关注我的公众号(Michael阿明),一起加油、一起学习进步!

Michael阿明

转载地址:https://michael.blog.csdn.net/article/details/101376680 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LeetCode 77. 组合(回溯)
下一篇:LeetCode 216. 组合总和 III(排列组合 回溯)

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2024年05月07日 03时50分54秒