力扣39. 组合总和

回溯

  • 思路:
    • 定义递归函数 dfs(candidates, target, idx),表示当前 candidates 在 idx 位,还剩 target 需要组合;
    • 递归终止条件:
      • target <= 0;
        • target == 0 时,将该组合存入结果数组;
      • candidates 元素已经用完,idx = candidates.size();
    • 在当前函数中,可以:
      • 跳过 candidates[idx] 元素进行组合,即 dfs(candidates, target, idx + 1) ;
      • 也可以使用 candidates[idx] 元素进行组合(因为可以使用重复元素),即 dfs(candidates, target - candidates[idx], idx)
class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        dfs(candidates, target, 0);
        return result;
    }

private:
    void dfs(std::vector<int>& candidates, int target, int idx) {
        if (idx == candidates.size()) {
            return;
        }
        if (target == 0) {
            result.emplace_back(item);
            return;
        }
        dfs(candidates, target, idx + 1);
        if (target - candidates[idx] >= 0) {
            item.emplace_back(candidates[idx]);
            dfs(candidates, target - candidates[idx], idx);
            item.pop_back();
        }
    }

private:
    std::vector<std::vector<int>> result;
    std::vector<int> item;
};

相关推荐

  1. 39. 组合总和

    2024-01-18 21:10:01       56 阅读
  2. 39组合总和

    2024-01-18 21:10:01       28 阅读
  3. 39. 组合总和 - (LeetCode)

    2024-01-18 21:10:01       31 阅读
  4. :40. 组合总和 II

    2024-01-18 21:10:01       45 阅读
  5. 组合总和2(40)

    2024-01-18 21:10:01       36 阅读

最近更新

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

    2024-01-18 21:10:01       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-18 21:10:01       106 阅读
  3. 在Django里面运行非项目文件

    2024-01-18 21:10:01       87 阅读
  4. Python语言-面向对象

    2024-01-18 21:10:01       96 阅读

热门阅读

  1. 关于OC中变量相关知识点

    2024-01-18 21:10:01       55 阅读
  2. MySQL中WITH AS语句的使用

    2024-01-18 21:10:01       61 阅读
  3. iOS长按时无法保存图片问题解决方案

    2024-01-18 21:10:01       85 阅读