Combination Sum II

发布时间:2019-06-29 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Combination Sum II脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

标签(空格分隔): C++ 算法 LeetCode 数组 中等 DFS

每日算法——leetcode系列


问题 Combination Sum II

Difficulty: Medium

Given a set 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.

  • Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 >≤ … ≤ ak).>

  • 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]

class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        
    }
};

翻译

和的组合

难度系数:中等

给定一个一些数组成的候选集合C,和一个目标数T。现从C中选出一些数,求所有不同的取数方案使其累加和恰好等于T。
C中的每个数都只能用一次。

注意

  • 所有的数(包括目标数)都为正整数

  • 组合中的元素(a1, a2, … , ak) 不能为降序排列。(ie, a1 ≤ a2 >≤ … ≤ ak)

  • 不能有重复的组合方案
    例如:候选集合10,1,2,7,6,1,5 和目标值8,

答案为:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]

思路

Combination Sum很像,只是这里不能重复取一个元素,但根据例子看是元素是有重复元素的。
这样就得去重复。

代码

class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        sort(candidates.begin(),candidates.end());
        len = static_cast<int>(candidates.size());
        temAndidates = candidates;
        vector<int> combination;
        dfs(combination, target, 0);
        return result;
    }
    
private:

    void dfs(vector<int>& combination, int remainder,  int tempLen){
        if (remainder == 0){
            result.push_back(combination);
            return;
        }
        if (tempLen >= len) {
            return;
        }
        int pre = -1; // 记录前一个数,去重复
        
        for (int i = tempLen; i < len; ++i) {
            if (pre == temAndidates[i]){
                continue;
            }
            if (remainder < temAndidates[i]){
                return;
            }
            pre = temAndidates[i];
            combination.push_back(temAndidates[i]);
            dfs(combination, remainder - temAndidates[i], i + 1); // i + 1代表下一个元素
            combination.pop_back();
        }
    }
    
    int len;
    vector<int> temAndidates;
    vector<vector<int> > result;
};

唠叨
力猫组网真是不讨好的事,电力猫容易坏,还贵,好几天没上网了,上不到网就像战士没枪的感觉,只不过还好,能看书。

脚本宝典总结

以上是脚本宝典为你收集整理的Combination Sum II全部内容,希望文章能够帮你解决Combination Sum II所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。