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] 

    使用递归的方法实现:

    #include<iostream>
    #include<vector>
    #include<algorithm>
    using namespace std;
    
    class Solution {
    public:
        vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
            if(candidates.empty())
                return vector<vector<int> >();
            sort(candidates.begin(),candidates.end());
            vector<vector<int> > ret;
            vector<int> path;
            combination(candidates,0,target,ret,path);
            return ret;
        }
    
        void combination(vector<int> &candidates,int start,int target,vector<vector<int> > &ret,vector<int> &path)
        {
            if(target<0)
                return;
            if(target==0)
            {
                ret.push_back(path);
                return;
            }
            int i;
            for(i=start;i<(int)candidates.size();i++)
            {
                path.push_back(candidates[i]);
                combination(candidates,i,target-candidates[i],ret,path);
                path.pop_back();
            }
        }
    };
    
    int main()
    {
        Solution s;
        vector<int> vec={2,3,6,7};
        vector<vector<int> > result=s.combinationSum(vec,7);
        for(auto a:result)
        {
            for(auto v:a)
                cout<<v<<" ";
            cout<<endl;
        }
    }

    运行结果:

  • 相关阅读:
    Oracle 不走索引
    Oracle不等值链接
    查看统计信息是否过期
    JavaScript利用append添加元素报错
    Subversion Native Library Not Available & Incompatible JavaHL library loaded
    Oracle并行查询出错
    Oracle连接出错(一)
    Linux下Subclipse的JavaHL
    Java生成文件夹
    Java生成文件
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4125608.html
Copyright © 2011-2022 走看看