39. 组合总和

这篇博客介绍了如何利用搜索算法和剪枝策略解决寻找数组中元素组合成特定目标数的问题。通过排序数组并进行递归搜索,当当前元素之和超过目标时停止后续搜索,从而减少无效计算。示例展示了在不同情况下如何找到所有可能的组合。代码实现中,时间复杂度为4ms,击败了98.79%的用户,内存使用10.7MB,击败了97.64%的用户。
摘要由CSDN通过智能技术生成

39. 组合总和

题目描述

给定一个 无重复元素 的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的数字可以无限制重复被选取。

说明:

  • 所有数字(包括 target)都是正整数。
  • 解集不能包含重复的组合。

示例1:

输入:candidates = [2,3,6,7], target = 7,
所求解集为:
[
  [7],
  [2,2,3]
]

示例2:

输入:candidates = [2,3,5], target = 8,
所求解集为:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

提示:

  • 1 ≤ c a n d i d a t e s . l e n g t h ≤ 30 1 \le candidates.length \le 30 1candidates.length30

  • 1 ≤ c a n d i d a t e s [ i ] ≤ 200 1 \le candidates[i] \le 200 1candidates[i]200

  • candidate 中的每个元素都是独一无二的。

  • 1 ≤ t a r g e t ≤ 500 1 \le target \le 500 1target500


题解:

搜索+剪枝。

一般这种凑某个数的题目,有一个常用的剪枝技巧:将数组排序,如果 sum + candidates[pos] > target ,可直接停止后面的递归。

对于此题,递归终止条件是:sum == target

代码:

class Solution {
public:
    vector<vector<int>> ret;
    vector<int> ans;
    void dfs( vector<int>& candidates, int p, int now, int target ) {
        if ( now == target ) {
            ret.push_back( ans );
            return;
        }
        for ( int i = p; i < candidates.size(); ++i ) {
            if ( now + candidates[i] <= target ) {
                ans.push_back( candidates[i] );
                dfs( candidates, i, now + candidates[i], target );
                ans.pop_back();
            }
        }
    }
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        sort( candidates.begin(), candidates.end() );
        if ( !candidates.size() || candidates[0] > target ) return {};
        dfs( candidates, 0, 0, target );
        return ret;
    }
};
/*
时间:4ms,击败:98.79%
内存:10.7MB,击败:97.64%
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值