您的位置:首页 > 其它

LeetCode39:Combination Sum

2015-07-06 20:58 393 查看
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]

这道题看过好几次最开始都没看出怎么做就一直留着,结果今天在做Subsets 这道题时找到了灵感,使用深度优先的方法搜索,并且用一个vector记录向量,找到合适的向量时即将它保存在结果中,并进行回溯操作。这道题相比于Subsets中使用回溯法而言更麻烦一些。以后需要注意这种解题方法,当要求解的结果是一系列向量的集合时使用dfs搜索记录路径这种方法。对于输入candidates=[1,2] ,target=3,遍历的方向如图:




runtime:28ms

class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        vector<vector<int>> result;
        vector<int> path;
        sort(candidates.begin(),candidates.end());
        helper(candidates,0,0,target,path,result);
        return result;
    }

void helper(vector<int> &nums,int pos,int base,int target,vector<int>& path,vector<vector<int>> & result)
    {
        if(base==target)
        {
            result.push_back(path);
            return ;
        }
        if(base>target)
            return ;
        for(int i=pos;i<nums.size();i++)
        {
            path.push_back(nums[i]);
            helper(nums,i,base+nums[i],target,path,result);
            path.pop_back();
        }
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: