组合求和2

题目描述:

Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.

Each number in candidates may only be used once in the combination.

Note: The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8
Output: 
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]

Example 2:

Input: candidates = [2,5,2,1,2], target = 5
Output: 
[
[1,2,2],
[5]
]

Constraints:

  • 1 <= candidates.length <= 100
  • 1 <= candidates[i] <= 50
  • 1 <= target <= 30

求解思路:

使用回溯(backtrack)算法。首先将原数组candidates按照取值从小到大排序,然后依次寻找可能求和等于目标值target的子数组。

构建一维动态数组combination存放可能成为候选的子数组,构建二维动态数组存放所有符合要求的子数组res。

回溯算法在子程序中完成,目标是依次遍历已排序的数组candidates中每个值,并判断当前值是否可以作为构成候选子数组的一份子。

(1)如果“目标值-当前求和=0”,也就是候选子数组的求和已经等于目标值,则结束当前回溯子过程,并把满足条件的候选子数组combination存入res中。

(2)依次遍历candidates数组时,当前值如果没有和前一个值重复,并且“目标值>= 当前求和+当前值”,则当前值有可能作为候选项。

从当前位置的下一个位置重新进入回溯子程序,直至找到满足条件的候选子数组,或者“目标值< 当前求和+当前值”,因为数组candidates已经从小到大排序,所以后续值也不可能满足条件了。

每个当前值在结束回溯子程序后,当前值都要从候选项子数组中弹出,也就是每个较小的值(当前求和+当前值<=目标值)都有可能在候选列表中,也有可能不在候选列表中,要兼顾两种情况。

代码:

vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        sort(candidates.begin(), candidates.end());
        vector<vector<int>> res;
        vector<int> combination;
        backtrack(res, combination, candidates, target, 0);
        return res;
    }
    void backtrack(vector<vector<int>> &res, vector<int> &combination, vector<int> &candidates, int target, int index){
        if (target ==0){
            res.push_back(combination);
            return;
        }
        for (int i = index; i<candidates.size()&& target>=candidates[i]; i++){
            if (i==index || candidates[i] != candidates[i-1]) {
                // not the same combination again
                combination.push_back(candidates[i]);
                backtrack(res, combination, candidates, target-candidates[i], i+1);
                combination.pop_back();
            }
        }
    }

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值