zoukankan      html  css  js  c++  java
  • Combination Sum

    Given a set of candidate numbers (C) 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.
    • Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
    • 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] 

    思路:在集合中找出组合之和为目标值的集合。这让我们很容易联想到01背包问题,递归回溯累加到目标值。

    class Solution {
    public:
        void resolve(vector<int> &candidates,int target,int start,int sum,vector<int> &path,vector<vector<int> > &result)
        {
            if(sum>target)
                return;
            if(sum==target)
            {
                result.push_back(path);
                return;
            }
            for(int i=start;i<candidates.size();i++)
            {
                path.push_back(candidates[i]);
                resolve(candidates,target,i,sum+candidates[i],path,result);
                path.pop_back();
            }
        }
        vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
            vector<vector<int> > result;
            vector<int> path;
            sort(candidates.begin(),candidates.end());
            result.clear();
            path.clear();
            resolve(candidates,target,0,0,path,result);
            return result;
        }
    };
  • 相关阅读:
    HDOJ 1241 Oil Deposits【最大连通块 dfs】
    POJ 3984 迷宫问题【迷宫最短路径 bfs】
    封装
    继承的另一种使用方式。。。
    类的绑定方法与继承
    XML模块与类的定义
    常用模块三
    python day19
    常用模块与项目目录规范
    python day17
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3688154.html
Copyright © 2011-2022 走看看