39. Combination Sum

来源:互联网 发布:mac 不显示隐藏文件 编辑:程序博客网 时间:2024/05/22 01:56

problem:

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.
  • 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]]
这道题使用深度搜索优先算法,对于每一种情况遍历压栈出栈。

class Solution {public:    vector<vector<int>> result;    vector<int> temp = {};    void dfs(vector<int> candidates, int target, int sum, int start)    {        if(sum == target)        {            result.push_back(temp);            //return;        }        else if(sum > target)        {            //return;        }        else        {            for(int i=start; i<candidates.size(); i++)            {                temp.push_back(candidates[i]);                dfs(candidates, target, candidates[i]+sum, i);                temp.pop_back();            }        }    }    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {        if(candidates.empty())            return result;        dfs(candidates, target, 0, 0);        return result;    }};


0 0
原创粉丝点击