博客
关于我
[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/

    你可能感兴趣的文章
    npm install 报错 EEXIST File exists 的解决方法
    查看>>
    npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
    查看>>
    npm install 报错 Failed to connect to github.com port 443 的解决方法
    查看>>
    npm install 报错 fatal: unable to connect to github.com 的解决方法
    查看>>
    npm install 报错 no such file or directory 的解决方法
    查看>>
    npm install 权限问题
    查看>>
    npm install报错,证书验证失败unable to get local issuer certificate
    查看>>
    npm install无法生成node_modules的解决方法
    查看>>
    npm install的--save和--save-dev使用说明
    查看>>
    npm node pm2相关问题
    查看>>
    npm run build 失败Compiler server unexpectedly exited with code: null and signal: SIGBUS
    查看>>
    npm run build报Cannot find module错误的解决方法
    查看>>
    npm run build部署到云服务器中的Nginx(图文配置)
    查看>>
    npm run dev 和npm dev、npm run start和npm start、npm run serve和npm serve等的区别
    查看>>
    npm run dev 报错PS ‘vite‘ 不是内部或外部命令,也不是可运行的程序或批处理文件。
    查看>>
    npm scripts 使用指南
    查看>>
    npm should be run outside of the node repl, in your normal shell
    查看>>
    npm start运行了什么
    查看>>
    npm WARN deprecated core-js@2.6.12 core-js@<3.3 is no longer maintained and not recommended for usa
    查看>>
    npm 下载依赖慢的解决方案(亲测有效)
    查看>>