LeetCode 39. Combination Sum && 40. Combination Sum II && 216. Combination Sum III

本文详细解析了三道关于组合总和的经典算法题,包括无限制重复选取元素、限制每种元素仅能选取一次及从特定范围内选取固定数量元素的情况,并提供了具体的实现代码。

39. Combination Sum

Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:

[
  [7],
  [2, 2, 3]
]

在所给的正数数组(不含重复元素)中,找出所有的元素组合使得它们的和等于目标值。这些找到的元素组合要以非递减顺序排列,这些组合不能够是重复的,但数组中元素可以重复使用。
看一下题目给出的例子:看看例子:[2,3,6,7], 7
搜索过程:

2开始进行搜索,由于允许重复:
2,2,2
接续重复2,和为8,大于7,所以退一步再从下一个数开始搜:
22
223
此时和=7,符合要求。后续的搜索:
226 不符
227 不符
233 不符
236 不符
237 不符
333 不符
336 不符
337 不符
......
67 不符
7 符合

通过这样的搜索过程就得到了需要的元素组合。思路是非常朴素的穷举,一个个尝试,试错了就退回——所以这里我们使用回溯法。

另写一个递归函数,加入三个变量,res保存所有已经得到的解,resItem是其中一个目标值组合解,index是当前搜索范围的起点。每次调用新的递归函数时,target减去当前数组元素:

vector<vector<int> > combinationSum(vector<int> &candidates, int target){
        vector<vector<int>> rs;
        if (candidates.size() == 0) return rs;

        sort(candidates.begin(),candidates.end());
        vector<int> resItem;
        dfs(candidates,rs,resItem,0,target);
        return rs;
    }

    //cdd是原数组,res是目标值组合集合,resItem是其中一个目标值组合解,index是当前搜索范围的起点,target是目标值
    void dfs(vector<int> &cdd ,vector<vector<int>> &res ,vector<int> &resItem ,int index ,int target){
        if (target == 0) {//表明已经找到所求组合
            res.push_back(resItem);
            return;
        }
        if (target < cdd[index]) return;//此时sum必定大于target
        for (int i = index ; i < cdd.size(); ++i){
            resItem.push_back(cdd[i]);
            dfs(cdd,res,resItem,i,target-cdd[i]);
            resItem.pop_back();//回溯
        }
    }

9ms通过。

第一版代码,没有用递归,15ms。

 vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        int cur = candidates.size() - 1;
        vector<vector<int>> rs;
        while (cur >= 0)
        {
            int remain = target - candidates[cur];
            if (remain == 0)
            {
                rs.push_back({ candidates[cur] });
            }
            else if (remain > 0)
            {
                auto beg = candidates.begin();
                vector<int> subCandidates = vector<int>(beg, beg + cur + 1);
                vector<vector<int>> temp = combinationSum(subCandidates, remain);
                if (temp.size() != 0) {
                    for (auto &item : temp) {
                        item.push_back(candidates[cur]);
                        rs.push_back(item);
                    }
                }
            }
            --cur;
        }
        return rs;
    }

40. Combination Sum II

Given a collection 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.
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]
]

本质没有区别,只是之前那道题给定数组中的数字可以重复使用,而这道题不能,而且这道题给定数组中可能有重复数字。所以改动的地方有两处:1.递归调用里的index传参要改为i+1;2.在递归的for循环里跳过数组中重复项。

vector<vector<int> > combinationSum2(vector<int> &candidates, int target){
        vector<vector<int>> rs;
        if (target <= 0 || candidates.size() == 0) return rs;//因为数组元素都是正数,所以目标值=0时必定找不到

        sort(candidates.begin(),candidates.end());
        vector<int> resItem;
        dfs(candidates,rs,resItem,0,target);
        return rs;
    }

    //cdd是原数组,res是目标值组合集合,resItem是其中一个目标值组合,index是当前搜索范围的起点,target是目标值
    void dfs(vector<int> &cdd ,vector<vector<int>> &res ,vector<int> &resItem ,int index ,int target){
        if (target == 0) {//表明已经找到所求组合
            res.push_back(resItem);
            return;
        }
        if (target < cdd[index]) return;//此时sum必定大于target
        for (int i = index ; i < cdd.size(); ++i){
            if (i > index && cdd[i] == cdd[i-1]) continue;
            resItem.push_back(cdd[i]);
            dfs(cdd,res,resItem,i+1,target-cdd[i]);
            resItem.pop_back();//回溯
        }
    }

第一版代码:

vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        sort(candidates.begin(), candidates.end());
        vector<vector<int>> rs;
        test(candidates, target, rs);
        return rs;
    }

    void test(vector<int>& candidates, int target, vector<vector<int>>&rs) {
        int cur = candidates.size() - 1;
        while (cur >= 0)
        {
            int remain = target - candidates[cur];
            if (remain == 0)
            {
                rs.push_back({ candidates[cur] });
            }
            else if (remain > 0)
            {
                auto beg = candidates.begin();
                vector<int> subCandidates = vector<int>(beg, beg + cur);
                vector<vector<int>> temp;
                test(subCandidates, remain, temp);
                if (temp.size() != 0) {


                    for (auto &item : temp){
                        item.push_back(candidates[cur]);
                        rs.push_back(item);
                    }
                }
            }
            while (cur > 0 && candidates[cur] == candidates[cur - 1])
            {
                --cur;
            }
            --cur;
        }
    }

216. Combination Sum III

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

Example 1:

Input: k = 3, n = 7

Output: [[1,2,4]]

Example 2:

Input: k = 3, n = 9

Output:
[[1,2,6], [1,3,5], [2,3,4]]

这道题跟之前两道有点不太一样。从1~9这九个数字中挑选k个不重复的数,使得它们的和等于n。但本质上还是差不多的。

vector<vector<int>> combinationSum3(int k, int n) {
        if (k > 9 || n < k*(k+1)/2 || n > (9-k + 1 + 9)*k/2) return{}; //(首项+末项)*项数/2
        vector<vector<int>> rs;
        vector<int> resItem;
        cs3dfs(rs,resItem,1,k,n);
        return rs;
    }
    void cs3dfs(vector<vector<int>> &res ,vector<int> &resItem ,int index , int k ,int n){
        if (n == 0 && resItem.size() == k) {res.push_back(resItem); return;}
        if (n < index) return;
        if (resItem.size() < k){
            for (int i = index ;i <= 9 ; ++i){
                resItem.push_back(i);
                cs3dfs(res,resItem,i+1,k,n-i);
                resItem.pop_back();
            }
        }
    }
<think>首先,用户意图是寻找满足特定数学性质的组合:组合中元素之和模2等于0,这等价于组合元素之和是偶数。用户的问题是“寻找组合使得组合元素之和是偶数”。 我需要作为专业智能搜索助手,根据用户意图和搜索词进行检索。用户意图已经很明确:寻找组合,使得元素之和为偶数的组合。搜索词可以是“组合元素之和为偶数”、“even sum combinations”等。 任务要求: 1. 调用网络搜索工具进行检索。 2. 整合检索到的内容,生成详细且清晰的回答,具有实用性和可操作性。 3. 禁止将所有引用内容集中在回答末尾。所以,我应该将引用融入回答中,而不是单独列出。 4. 避免使用第一人称如“我”。 5. 避免步骤词汇如“首先”、“然后”。 6. 尽量将答案组织为多个方法或步骤,并在每个步骤间换行。 7. 对于代码和公式,遵循特定格式:行内公式用$ $,独立公式用$$ $$,代码用三个反引号指定语言。 8. 在回答完后,添加相关问题部分:使用“§§相关问题§§:”作为标题,不换行,列出至少3个相关问题,基于用户问题和回答内容。 回答结构: - 组织为多个方法或步骤,每个步骤间换行。 - 避免使用“首先”、“然后”等词。 - 提供实用性和可操作性的内容。 可能的搜索内容: - 数学概念:组合元素之和为偶数的条件。这通常涉及奇偶性。对于一个集合,元素之和为偶数当且仅当奇数的个数是偶数(因为奇数+奇数=偶数,偶数+偶数=偶数,奇数+偶数=奇数)。 - 算法:如何生成所有这样的组合,或者计数这样的组合。 - 应用:在编程或数学问题中如何实现。 检索后整合: 假设我搜索到: - 在组合数学中,对于一个集合,满足元素之和为偶数的组合数量取决于奇数和偶数的个数。 - 设集合中有o个奇数,e个偶数。 - 那么,一个组合的元素之和为偶数当且仅当组合中奇数的个数是偶数(包括0)。 - 因此,满足条件的组合数为:从o个奇数中选择偶数个奇数的选择方式数乘以从e个偶数中选择任意个数的选择方式数。 - 数学公式:总和为 $\sum_{k=0}^{\lfloor o/2 \rfloor} \binom{o}{2k} \times 2^e$,因为对于每个偶数,可以选择或不选择,不影响奇偶性。 - 更精确地说,从o个奇数中选择偶数个的方法数是 $\binom{o}{0} + \binom{o}{2} + \binom{o}{4} + \cdots = 2^{o-1}$(当o>0时),因为二项式系数的和。 - 实际上,$\sum_{k \text{ even}} \binom{o}{k} = 2^{o-1}$ 对于 o >=1。 - 而偶数的选择:每个偶数可以选或不选,所以有 $2^e$ 种方式。 - 因此,总组合数为 $2^{o-1} \times 2^e = 2^{o+e-1} = 2^{n-1}$,其中n是元素总数,假设集合非空。 - 但这是所有子集的数量的一半,因为一半子集和是偶数,一半是奇数(如果至少有一个奇数)。 对于生成组合,我可以提供算法。 在编程中,如何生成所有和偶数的组合。 回答组织: - 方法1:数学原理 – 解释条件。 - 方法2:计数满足条件的组合数。 - 方法3:生成所有这样的组合的算法(伪代码或代码)。 每个方法间换行。 代码格式:如果包含代码,用三个反引号指定语言。 公式:行内用$ $,独立用$$ $$。 最后,添加相关问题部分。 现在,生成回答。 首先,解释用户问题:用户想找到组合(子集),使得元素之和为偶数。 关键点:元素之和模2等于0,即和是偶数。 条件:组合中奇数的个数必须是偶数。 因为: - 每个奇数贡献1 mod 2,偶数贡献0 mod 2。 - 所以总和 mod 2 等于 奇数个数 mod 2。 - 因此,总和为偶 iff 奇数个数为偶。 所以,方法: 1. 识别集合中的奇数和偶数。 2. 选择偶数个奇数(包括0)和任意个偶数。 对于计数: - 如果集合有 o 个奇数,e 个偶数。 - 满足条件的组合数:$2^{e} \times \sum_{k \text{ even}} \binom{o}{k} = 2^{e} \times 2^{o-1} = 2^{o+e-1}$,当 o >=1。 - 如果 o=0,所有元素为偶数,所有组合和都是偶数,所以有 $2^{e} = 2^{n}$ 个。 - 类似地,如果 o>=1,总子集数 $2^{n}$,一半和偶,一半和奇。 所以,在回答中,提供这些。 对于生成组合: - 在编程中,可以使用回溯法生成所有子集,检查每个子集的和是否偶,但效率低。 - 更聪明的方法:基于奇偶性。 - 生成所有选择:选择一组偶数个奇数,和任意子集的偶数。 - 但任意子集的偶数可以独立处理。 算法: - 分组:将元素分为奇数集和偶数集。 - 对于奇数集,生成所有子集,其中元素个数为偶数。 - 对于偶数集,生成所有子集。 - 然后,组合:每个满足条件的子集是 一个偶数个奇数的子集 并上 一个偶数的子集。 在代码中,可以实现。 提供示例代码。 假设语言:Python,常见。 代码示例: ```python def generate_even_sum_combinations(elements): # Separate elements into odd and even odds = [x for x in elements if x % 2 != 0] evens = [x for x in elements if x % 2 == 0] # Generate all subsets for evens: each element can be included or not from itertools import chain, combinations even_subsets = chain.from_iterable(combinations(evens, r) for r in range(len(evens)+1)) # Generate all subsets of odds with even size odd_subsets = [] for r in range(0, len(odds)+1, 2): # r even: 0,2,4,... odd_subsets.extend(combinations(odds, r)) # Combine: for each even subset and each odd subset, combine result = [] for even_sub in even_subsets: for odd_sub in odd_subsets: combo = list(even_sub) + list(odd_sub) result.append(combo) return result # Example usage elements = [1,2,3,4] combos = generate_even_sum_combinations(elements) print(combos) # This will print all combinations with even sum ``` 但注意,这个代码可能效率不高,因为生成了所有子集,对于大n不实用。但作为示例。 在回答中,解释原理。 组织为步骤: - 步骤1:理解元素之和为偶数的条件。 - 步骤2:计算满足条件的组合数量。 - 步骤3:生成所有满足条件的组合的方法。 每个步骤间换行。 避免步骤词汇,所以直接用标题或描述。 例如: **条件分析** 解释数学条件。 **组合计数** 给出公式。 **组合生成** 描述算法并提供代码。 最后,相关问题。 相关问题基于用户问题和回答: 用户问题:寻找组合使得元素之和是偶数。 回答:关于条件、计数、生成。 所以,相关问题: 1. 如何高效生成所有和偶数的组合? 2. 如果元素有重复,如何处理? 3. 对于大集合,如何近似计数或采样? 4. 应用在编程问题中。 至少三个。 格式: §§相关问题§§: 1. 问题1 2. 问题2 3. 问题3 标题不换行。 现在,草拟回答。</think>### 条件分析 元素之和为偶数的组合要求组合中奇数的个数为偶数(包括0)。每个元素对总和的奇偶性贡献:奇数元素使总和奇偶性变化,偶数元素不影响。因此,给定一个集合,需识别奇数和偶数元素:设 $o$ 为奇数个数,$e$ 为偶数个数,总和 $n = o + e$。 ### 组合计数 满足条件的组合总数取决于 $o$ 和 $e$: - 如果 $o = 0$(全为偶数),所有子集均满足,组合数为 $2^e$。 - 如果 $o \geq 1$,组合数为 $2^{o+e-1} = 2^{n-1}$。 数学推导:选择任意偶数子集($2^e$ 种方式),并从奇数中选择偶数个元素($\sum_{k \text{ even}} \binom{o}{k} = 2^{o-1}$ 种方式)。总数为 $2^{e} \times 2^{o-1} = 2^{n-1}$。 ### 组合生成算法 分组生成方法: 1. 将集合分为奇数集和偶数集。 2. 生成所有偶数子集(每个偶数可选或不选)。 3. 生成所有奇数子集,其中元素个数为偶数(例如大小0,2,4,...)。 4. 组合每个偶数子集和每个奇数子集。 Python 实现示例(使用 `itertools`): ```python import itertools def generate_even_sum_combinations(elements): # 分离奇数和偶数 odds = [x for x in elements if x % 2 != 0] evens = [x for x in elements if x % 2 == 0] # 生成所有偶数子集 even_subsets = [] for r in range(len(evens) + 1): even_subsets.extend(itertools.combinations(evens, r)) # 生成所有奇数子集(元素个数为偶数) odd_subsets = [] for r in range(0, len(odds) + 1, 2): # r 为偶数:0,2,4,... odd_subsets.extend(itertools.combinations(odds, r)) # 组合所有子集 result = [] for even_sub in even_subsets: for odd_sub in odd_subsets: combo = list(even_sub) + list(odd_sub) if combo: # 避免空组合 result.append(combo) return result # 示例使用 elements = [1, 2, 3, 4] combinations = generate_even_sum_combinations(elements) print(combinations) # 输出所有和偶数的组合 ``` 注意:此方法适用于小型集合;对于大型集合,考虑优化(如动态规划)以避免指数级复杂度。 ### 实际应用 - 在编程中,应用于子集和问题或组合优化(如 LeetCode 问题)。 - 数学建模:用于概率计算或密码学中奇偶校验。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值