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

    你可能感兴趣的文章
    NLP:使用 SciKit Learn 的文本矢量化方法
    查看>>
    nmap 使用方法详细介绍
    查看>>
    Nmap扫描教程之Nmap基础知识
    查看>>
    nmap指纹识别要点以及又快又准之方法
    查看>>
    Nmap渗透测试指南之指纹识别与探测、伺机而动
    查看>>
    Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
    查看>>
    NMAP网络扫描工具的安装与使用
    查看>>
    NMF(非负矩阵分解)
    查看>>
    nmon_x86_64_centos7工具如何使用
    查看>>
    NN&DL4.1 Deep L-layer neural network简介
    查看>>
    NN&DL4.3 Getting your matrix dimensions right
    查看>>
    NN&DL4.7 Parameters vs Hyperparameters
    查看>>
    NN&DL4.8 What does this have to do with the brain?
    查看>>
    nnU-Net 终极指南
    查看>>
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    NO 157 去掉禅道访问地址中的zentao
    查看>>
    no available service ‘default‘ found, please make sure registry config corre seata
    查看>>
    No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
    查看>>
    no connection could be made because the target machine actively refused it.问题解决
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>