LeetCode 40 Combination Sum II

本文介绍了一个算法问题——组合总和 II 的解决方案。该问题要求在集合中找出所有可能的组合,使得组合内的数字之和等于目标值 target。文章提供了一段 C++ 代码实现,通过递归深度优先搜索 (DFS) 方法来解决该问题,并确保每种数字在集合中仅被使用一次。

题意:

集合中的每个数字只能使用一次,求出所有数字和为target的方案。


思路:

如果把集合中的数字计数,问题会变得和 http://blog.youkuaiyun.com/houserabbit/article/details/72677176 几乎一致。

我的方法思路与计数思路几乎一致,只不过我没有合并数字,而是枚举每种数字个数的时候只取排在后面的数字,这样就保证了方案不重复。


代码:

class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int> &candidates, int target) {
        n = candidates.size();
        count = new int[n];
        vector<vector<int>> ans;
        sort(candidates.begin(), candidates.end());
        dfs(n - 1, target, ans, candidates);
        return ans;
    }

private:
    int n;
    int *count;

    void dfs(int idx, int target, vector<vector<int>> &ans, vector<int> &candidates) {
        if (candidates[idx] <= target &&
            (idx == n - 1 || candidates[idx] != candidates[idx + 1] || count[idx + 1] == 1)) {
            count[idx] = 1;
            int newtar = target - candidates[idx];
            if (newtar == 0) {
                vector<int> res;
                for (int i = idx; i < n; ++i) {
                    if (count[i] == 1) {
                        res.push_back(candidates[i]);
                    }
                }
                ans.push_back(res);
            } else if (idx > 0) {
                dfs(idx - 1, newtar, ans, candidates);
            }
        }
        count[idx] = 0;
        if (idx > 0) {
            dfs(idx - 1, target, ans, candidates);
        }
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值