首页 > 其他 > 详细

17 Combination Sum II

时间:2019-08-20 23:57:01      阅读:141      评论:0      收藏:0      [点我收藏+]

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

Each number in candidates 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.
Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]]
Example 2:

Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
[1,2,2],
[5]]

这道题目本质上还是Combination Sum 问题的一个变化,其关键之处就在于排除重复项,即本身元素不重复出现,如果同一层出现相同元素则忽视后面的元素。重复项的问题可以用以下一张图片来概括。假设给定的序列 [ 1, 2, 2, 2, 5], 目标值是5,则有:

技术分享图片

故而在Combination Sum 答案的基础上进行了改进, 代码如下:

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

17 Combination Sum II

原文:https://www.cnblogs.com/xiaoyisun06/p/11385636.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!