力扣--深度优先算法/回溯算法39.组合总和

思路分析:

  1. 深度优先搜索 (DFS): 通过递归实现,尝试从给定的数字集合 candidates 中选择可能的数字,构建和为 target 的组合。
  2. 递归函数 dfs
    • 接收参数:candidates 为数字集合,target 为目标和,start 为当前选择的数字起始位置,nownum 为当前组合的和。
    • 遍历当前可能的数字,如果当前数字加上当前组合的和已经超过目标值 target,则跳过当前数字。
    • 将当前数字加入临时结果集 path,更新当前组合的和 nownum
    • 如果当前组合的和等于目标值 target,将临时结果集加入最终结果集 result
    • 否则,继续递归生成组合,注意起始位置更新为 i,可以重复使用当前数字。
    • 回溯过程中,撤销选择,继续尝试其他可能的组合。
  3. 主函数:
    • 创建空的结果集 result 和临时结果集 path
    • 调用深度优先搜索函数 dfs,从起始位置 0 和当前和 0 开始生成组合。
    • 返回最终结果。
class Solution {
    // 存储最终结果的二维数组
    vector<vector<int>> result;

    // 存储当前正在生成的组合的临时结果
    vector<int> path;

    // 定义深度优先搜索函数,用于生成组合
    void dfs(vector<int>& candidates, int target, int start, int nownum) {
        // 遍历当前可能的数字
        for (int i = start; i < candidates.size(); i++) {
            // 如果当前数字加上当前和已有和超过目标值 target,则跳过当前数字
            if (candidates[i] + nownum > target)
                continue;

            // 将当前数字加入临时结果集
            path.push_back(candidates[i]);
            nownum += candidates[i];

            // 如果当前和等于目标值 target,则将临时结果集加入最终结果集
            if (nownum == target)
                result.push_back(path);
            else
                // 继续递归生成组合,注意起始位置更新为 i,可以重复使用当前数字
                dfs(candidates, target, i, nownum);

            // 回溯,撤销选择,继续尝试其他可能的组合
            nownum -= candidates[i];
            path.pop_back();
        }
        return;
    }

public:
    // 主函数,生成和为 target 的所有组合
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        // 调用深度优先搜索函数,从起始位置 0 和当前和 0 开始生成组合
        dfs(candidates, target, 0, 0);

        // 返回最终结果
        return result;
    }
};

相关推荐

  1. 39. 组合总和

    2024-03-14 11:20:01       55 阅读
  2. 39组合总和

    2024-03-14 11:20:01       28 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-14 11:20:01       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-14 11:20:01       106 阅读
  3. 在Django里面运行非项目文件

    2024-03-14 11:20:01       87 阅读
  4. Python语言-面向对象

    2024-03-14 11:20:01       96 阅读

热门阅读

  1. 设计模式 — — 工厂模式

    2024-03-14 11:20:01       39 阅读
  2. - 概述 - 《设计模式(极简c++版)》

    2024-03-14 11:20:01       36 阅读
  3. c++qt函数中如何返回一个类对象或对象的引用

    2024-03-14 11:20:01       49 阅读
  4. Nginx和Ribbon实现负载均衡的区别

    2024-03-14 11:20:01       43 阅读
  5. 【OJ】K 个一组翻转链表

    2024-03-14 11:20:01       45 阅读
  6. Stream流

    Stream流

    2024-03-14 11:20:01      35 阅读
  7. Spring Boot 自动配置原理

    2024-03-14 11:20:01       38 阅读
  8. MATLAB使用OMP实现图像的压缩感知实例

    2024-03-14 11:20:01       39 阅读
  9. BACnet device对象详解以及协议栈相关代码

    2024-03-14 11:20:01       28 阅读