首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 40. 组合总和 II(排列组合 回溯)

LeetCode 40. 组合总和 II(排列组合 回溯)

作者头像
Michael阿明
发布2020-07-13 15:15:43
3970
发布2020-07-13 15:15:43
举报

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 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

-类似题目 LeetCode 216. 组合总和 III(排列组合 回溯) LeetCode 39. 组合总和(排列组合 回溯)

2. 回溯求解

class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        sort(candidates.begin(), candidates.end());
        vector<vector<int>> ans;
        vector<int> subset;
        bt(0,0,target,subset,ans,candidates);
        return ans;
    }
    void bt(int i, int sum, int &target, vector<int> subset, vector<vector<int>> &ans, vector<int> &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();
    	}
    }
};
在这里插入图片描述
在这里插入图片描述
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 题目
  • 2. 回溯求解
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档