码迷,mamicode.com
首页 > 其他好文 > 详细

【Combination Sum 】cpp

时间:2015-05-28 15:44:29      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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]

代码:

class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
            vector<vector<int> > ret;
            vector<int> tmp; 
            int sum = 0;
            std::sort(candidates.begin(), candidates.end());
            Solution::dfs(ret, tmp, sum, candidates, 0, candidates.size()-1, target);
            return ret;
    }
    static void dfs( 
            vector<vector<int> >& ret, 
            vector<int>& tmp, 
            int &sum,
            vector<int>& candidates, 
            int begin, 
            int end, 
            int target )
    {
            if ( sum>target ) return;
            if ( sum==target )
            {
                ret.push_back(tmp);
                return;
            }
            for ( int i=begin; i<=end; ++i )
            {
                if ( sum+candidates[i]<=target )
                {
                    sum += candidates[i];
                    tmp.push_back(candidates[i]);
                    Solution::dfs(ret, tmp, sum, candidates, i, end, target);
                    sum -= candidates[i];
                    tmp.pop_back();
                }
            }
    }
};

tips:

采用深搜模板:

1. 终止条件sum>target

2. 加入解集条件sum==target

3. 遍历当前层所有分支(如果满足sum+candidates[i]<target,则还可以再往上加candidates[i];注意,这里传入下一层的begin下标为i,因为要求元素可以无限多重复)

4. 由于传入下一层始终满足begin<=end,因此不要在终止条件中加入(begin>end)

【Combination Sum 】cpp

标签:

原文地址:http://www.cnblogs.com/xbf9xbf/p/4535900.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!