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

【LeetCode】Combination Sum

时间:2014-09-09 10:54:08      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   os   io   使用   ar   

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] 

 

寻找target成员的过程中,如果candidates[i]是组成target的成员之一,那么寻找target-candidates[i]的子问题与原题就完全一致,因此是典型的递归。

参数列表中:result设为全局变量,用于记录所有可行的路径,因此使用引用(&);curPath是每次递归栈中独立部分,因此使用拷贝复制

对candidates的排序及去重的目的就是防止结果的重复,比如7 --> 2,2,3/2,3,2/3,2,2

class Solution 
{
public:
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) 
    {
        vector<vector<int> > result;
        //排序
        sort(candidates.begin(), candidates.end());
        //去重
        vector<int>::iterator iter = unique(candidates.begin(), candidates.end());
        candidates.erase(iter, candidates.end());

        vector<int> curPath;
        searchPath(candidates, result, curPath, 0, target);
        return result;
    }

    void searchPath(vector<int> &candidates, vector<vector<int> > &result, vector<int> curPath, int index, int target)
    {
        for(int i = index; i < candidates.size() && candidates[i] <= target; i ++)
        {
            if(candidates[i] < target)
            {
                curPath.push_back(candidates[i]);
                //此处仍为index,不能+1,同元素可以重复多次
                searchPath(candidates, result, curPath, i, target-candidates[i]);
                curPath.pop_back();
            }
            else// if(candidates[i] == target)
            {//结束
                curPath.push_back(candidates[i]);
                result.push_back(curPath);
                return;
            }
        }
    }
};

bubuko.com,布布扣

【LeetCode】Combination Sum

标签:des   style   blog   http   color   os   io   使用   ar   

原文地址:http://www.cnblogs.com/ganganloveu/p/3961332.html

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