博客
关于我
[LeetCode] 40. Combination Sum II
阅读量:249 次
发布时间:2019-03-01

本文共 1151 字,大约阅读时间需要 3 分钟。

回溯法是解决组合数问题的一种高效方法。以下是基于回溯法实现的组合数问题解决方案:

#include 
#include
using namespace std;void cb2help(vector
&res, vector
&v, int target, int i, vector
&recp) { if (target < 0) return; if (target == 0) { res.push_back(recp); return; } for (unsigned int k = i; k < v.size(); ++k) { if (k > i && v[k] == v[k-1]) continue; recp.push_back(v[k]); cb2help(res, v, target - v[k], k + 1, recp); recp.pop_back(); if (target - v[k] < 0) return; }}vector
combinationSum2(vector
v, int target) { sort(v.begin(), v.end()); vector
res; vector
recp; cb2help(res, v, target, 0, recp); return res;}

代码主要包含以下几个部分:

  • void cb2help 函数:这是回溯法的核心函数,负责从当前位置开始,尝试所有可能的数值组合。
  • combinationSum2 函数:这是最终的入口函数,负责对数组进行排序并调用回溯函数。
  • 回溯法的实现逻辑:从当前索引开始,遍历所有可能的数值。如果当前数值与前一个数值相同,则跳过;否则,将其加入当前组合,递归调用回溯函数,并在返回时移除当前数值,继续尝试下一个数值。
  • 需要注意的点是:当当前层的数值与前一个数值相同时,会跳过。这样可以避免重复计算相同的组合数。

    回溯法的时间复杂度主要取决于组合数的数量级。如果目标组合数较小,回溯法的效率较高;但如果目标组合数较多,可能会导致性能问题。

    转载地址:http://erfx.baihongyu.com/

    你可能感兴趣的文章
    NotImplementedError: Could not run torchvision::nms
    查看>>
    nova基于ubs机制扩展scheduler-filter
    查看>>
    Now trying to drop the old temporary tablespace, the session hangs.
    查看>>
    nowcoder—Beauty of Trees
    查看>>
    np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
    查看>>
    np.power的使用
    查看>>
    NPM 2FA双重认证的设置方法
    查看>>
    npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
    查看>>
    npm build报错Cannot find module ‘webpack‘解决方法
    查看>>
    npm ERR! ERESOLVE could not resolve报错
    查看>>
    npm ERR! fatal: unable to connect to github.com:
    查看>>
    npm ERR! Unexpected end of JSON input while parsing near '...on":"0.10.3","direc to'
    查看>>
    npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
    查看>>
    npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
    查看>>
    npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
    查看>>
    npm install CERT_HAS_EXPIRED解决方法
    查看>>
    npm install digital envelope routines::unsupported解决方法
    查看>>
    npm install 卡着不动的解决方法
    查看>>
    npm install 报错 EEXIST File exists 的解决方法
    查看>>
    npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
    查看>>