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

leetcode -- Combination Sum

时间:2015-03-06 22:17:47      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:leetcode   c   

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]

思路

T=a1+a2+...+ak,首先固定某一个元素ai(1ik),则剩余元素相加等于T?ai.而剩余元素相加可以如下递归vector<vector<int> > pre = combinationSum(c, target - *i)。其中的一个目的是为了快速减小target(以至target=a1甚至target<a1).

class Solution {
public:
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        vector<vector<int> > ret;
        vector<int>::iterator i, cbeg = candidates.begin(), cend = candidates.end();
        sort(cbeg, cend);
        for(i = cbeg; i < cend; i++){
            if(*i == target){    //既是递归出口也是一种case
                vector<int> tmp(1, *i);
                ret.push_back(tmp);
            }
            else if(*i < target){
                vector<int> c(i, cend);
                //先确定一个元素*i,再进行递归,将target逐步变小
                vector<vector<int> > pre = combinationSum(c, target - *i);  
                if(!pre.empty()){   //如果非空,则将*i元素添加至各个组合中
                    for(vector<vector<int> >::iterator vec = pre.begin(); vec < pre.end(); vec++){
                        (*vec).push_back(*i);
                        sort((*vec).begin(), (*vec).end());
                    }
                    //将某一固定*i元素下,所有符合要求的组合添加至最终结果
                    ret.insert(ret.end(), pre.begin(), pre.end());  
                }
            }
            else  break;
        }
        return ret;
    }
};

leetcode -- Combination Sum

标签:leetcode   c   

原文地址:http://blog.csdn.net/isunn/article/details/44104925

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