【深度优先搜索DFS】Lintcode 153. 数字组合 II

Lintcode 153. 数字组合 II

题目描述:给定一个数组 num 和一个整数 target. 找到 num 中所有的数字之和为 target 的组合.
在这里插入图片描述
Lintcode 135. 数字组合的简单变形,只是去除重复的时候考虑有些不同。

class Solution {
public:
    /**
     * @param num: Given the candidate numbers
     * @param target: Given the target number
     * @return: All the combinations that sum to target
     */
    vector<vector<int>> combinationSum2(vector<int> &num, int target) {
        vector<vector<int>> result;
        if (0 == num.size()) {
            return result;
        }
        
        sort(num.begin(), num.end());
        vector<int> combinations;
        helper(num, target, 0, combinations, result);
        return result;
    }
    
    
    //递归函数的定义
    /**
     *找到所有以combination开头的那些和为target的组合
     *并丢到result里,其中剩余的需要加入num里的数的和为remianTarget
     * 并且下一个可以加入combination中的数至少从num的startIdx开始(这样可以保证每个数可以取多次)
     */
    void helper(vector<int> &num, int remianTarget, int startIdx, vector<int> &combinations, vector<vector<int>> &result) {
        //递归的出口
        if (0 == remianTarget) {
            result.push_back(combinations);
            return;
        }
        
        //递归的拆解(针对num中每个元素)
        for (int i = startIdx; i < num.size(); ++i) {
            if (remianTarget < num[i]) {
                break;
            }
            
            // num = [1,1,1,2]  target = 4
            // 情况1:^ ^   ^
            // 情况2:  ^ ^ ^
            // 需要去除上面这种组合之间的重复
            if (num[i] == num[i - 1] && i != startIdx) {
                continue;
            }
            
            combinations.push_back(num[i]);
            helper(num, remianTarget - num[i], i + 1, combinations, result);
            combinations.pop_back();
        }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值