LeetCode 40. Combination Sum II(给定和,求组合Ⅱ)

题目描述:

    Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
    Each number in C may only be used once in the combination.
    Note:
        All numbers (including target) will be positive integers.
        The solution set must not contain duplicate combinations.
    For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8,
    A solution set is: 

[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

分析:
    题意:给定一个候选正整型可重复数字集合,一个正整型目标值target,找到所有的组合:任意选择集合中的数字,每个位置最多一次,使得它们的和为目标值。返回所有符合条件的组合。
    思路:这道题是LeetCode 39的进化版本,总体思想都是采用DFS搜索。这里主要说明几个不同点:① 每次找到一组解,都要判断跟之前的解是否重复(存在重复数字问题);② 每次搜索第k个数,不论是否把它加入sum中,接下来都从第k + 1个数开始搜索(每个位置只搜索一次)。最后返回所有不重复的解。

代码:

#include <bits/stdc++.h>

using namespace std;

class Solution {
private: 
	vector<vector<int>> ans;
	vector<int> res;
	
	void DFS(vector<int>& candidates, int target, int sum, int n, int k){
		if(target == sum){
			if(find(ans.begin(), ans.end(), res) == ans.end()){
				ans.push_back(res);
			}
			return;
		}
		if(k == n || sum > target){
			return;
		}
		res.push_back(candidates[k]);
		DFS(candidates, target, sum + candidates[k], n, k + 1);
		res.pop_back();
		DFS(candidates, target, sum, n, k + 1);
	}

public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
		ans.clear();
		res.clear();
		int n = candidates.size();
		// Exceptionl Case: 
		if(n == 0){
			return ans;
		}
		// sort
		sort(candidates.begin(), candidates.end());
        DFS(candidates, target, 0, n, 0);
		return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值