zoukankan      html  css  js  c++  java
  • LeetCode 39. 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]
    ]
    

    完全背包输出所有路径问题

    可以用完全背包求一遍,用vector<int>来维护所有到达该点的前驱结点。

    然后从目标位置,开始往前搜索。注意剪枝一下, 可以去除重复路径。

    class Solution
    {
        void dfs(vector<vector<int>> &vec, int target, int pro, vector<vector<int>> &ans, vector<int> res)
        {
            for(auto &f : vec[target])
            {
                if(target - f > pro)
                    return ;
                res.push_back(target - f);
    
                if(f != 0)
                    dfs(vec, f, target-f, ans, res);
                else
                    ans.push_back(res);
                res.pop_back();
            }
        }
    
    public:
        vector<vector<int>> combinationSum(vector<int>& candidates, int target)
        {
            sort(candidates.begin(), candidates.end());
    
            vector<bool> dp(target+1, false);
            dp[0] = true;
    
            vector<vector<int>>vec(target+1);
    
            for(int i = 0; i < candidates.size(); ++ i)
            {
                for(int j = candidates[i]; j <= target; ++ j)
                {
                    if(dp[j-candidates[i]])
                    {
                        dp[j] = true;
                        vec[j].push_back(j-candidates[i]);
                    }
                }
            }
            vector<vector<int>>ans;
    
            dfs(vec, target, target, ans, vector<int> {});
    
            return ans;
        }
    };
    
  • 相关阅读:
    [bochs]反编译的代码只能参考参考
    [Linux命令]dd
    exp1orer.exe木马解除方法
    江民公布“密码7005”最新变种技术报告
    广外女生1次惊心动魄的卸载
    [病毒]exp1orer.exe
    [Win2003]禁用关机原因调查
    获得本机IP地址
    一段连接FTP的VC代码
    [Perl]FTP自动上传文件的脚本以及配置文件
  • 原文地址:https://www.cnblogs.com/aiterator/p/6606741.html
Copyright © 2011-2022 走看看