zoukankan      html  css  js  c++  java
  • [LeetCode] Combination Sum

    Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

    The same repeated number may be chosen from C unlimited number of times.

    Note:

    • All numbers (including target) will be positive integers.
    • The solution set must not contain duplicate combinations.

    For example, given candidate set [2, 3, 6, 7] and target 7
    A solution set is: 

    [
      [7],
      [2, 2, 3]
    ]

    使用回溯法求解。

    主要是对于辅助函数helper的构建

    void helper(vector<vector<int>>& res, vector<int>& tmp, vector<int>& candidates, int target, int idx);

    idx为遍历的头索引。

    helper(res, tmp, candidates[i], target - candidates[i], i);

    每次将target更新为选择池中的剩余目标值。i不变是因为组成target的值允许重复。

    class Solution {
    public:
        vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
            vector<vector<int>> res;
            vector<int> tmp;
            int idx = 0;
            helper(res, tmp, candidates, target, idx);
            return res;
        }
        
        void helper(vector<vector<int>>& res, vector<int>& tmp, vector<int>& candidates, int target, int idx) {
            if (target < 0) {
                return;
            }
            else if (target == 0) {
                res.push_back(tmp);
            }
            else {
                for (int i = idx; i < candidates.size(); i++) {
                    tmp.push_back(candidates[i]);
                    helper(res, tmp, candidates, target - candidates[i], i);
                    tmp.pop_back();
                }
            }
        }
    };
    // 16 ms
  • 相关阅读:
    Burp Suite Professional单文件精简版该如何使用?
    快速掌握WinDBG
    Baymax大白补丁打油诗
    学员达标后完成的作业
    5星命名法:掌握这个软件全省
    挖掘IDA不可缺少的插件
    JEB安装和使用视频教程系列
    Ollydbg/x32dbg/x64dbg堆栈回溯要点总结
    Ollydbg狩猎从入门到精通
    Ollydbg/x32dbg爆破与逆向八法
  • 原文地址:https://www.cnblogs.com/immjc/p/8353396.html
Copyright © 2011-2022 走看看