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

    你可能感兴趣的文章
    Python 3 中未定义名称“xrange“
    查看>>
    python进阶(5):魔术方法篇(1)
    查看>>
    Python 3 范围与 Python 2 范围
    查看>>
    Python 3 读取ini文件
    查看>>
    Python 3.0 使用 turtle.onclick
    查看>>
    Python 3.10 明年发布,看看都有哪些新特性?
    查看>>
    python 3.10上安装pyqt5
    查看>>
    Python 3.12 正式发布了!
    查看>>
    Python 3.2 中的蛮力脚本
    查看>>
    Python 3.4 多处理递归 Pool.map()
    查看>>
    Python 3.4:未知格式代码“x“
    查看>>
    Python 3.5、ldap3 和 modify_password()
    查看>>
    python 3.6.8 升级至3.9版本升级
    查看>>
    Python 3.9 到 Python 3.12 的发展历程与区别
    查看>>
    python 32位和64位的区别在哪
    查看>>
    Python 3:何时使用 dict,何时使用元组列表?
    查看>>
    Python 3d 绘图 - 轴居中
    查看>>
    python ==》 字典
    查看>>
    python anaconda 安装使用
    查看>>
    python and或or 当参数传递的时候的用法
    查看>>