首页 > 其他 > 详细

leetcode笔记:Combination Sum

时间:2015-11-26 15:21:31      阅读:267      评论: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. (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]

二. 题目分析

题目大意是:有一个正整数集合C,和一个正整数目标T。现从C中选出一些数,使其累加和恰好等于T(C中的每个数都可以取若干次),求所有不同的取数方案。一道典型的DFS题。

三. 示例代码

// 来源:http://blog.csdn.net/doc_sgl/article/details/12283675
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;

class Solution 
{
private:
    void comb(vector<int> candidates, int index, int sum, int target, vector<vector<int>> &res, vector<int> &path)
    {
        if(sum>target)return;
        if(sum==target){res.push_back(path);return;}
        for(int i= index; i<candidates.size();i++)
        {
            path.push_back(candidates[i]);
            comb(candidates,i,sum+candidates[i],target,res,path);
            path.pop_back();
        }
    }

public:
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        // Note: The Solution object is instantiated only once.
        sort(candidates.begin(),candidates.end());
        vector<vector<int>> res;
        vector<int> path;
        comb(candidates,0,0,target,res,path);
        return res;
    }
};

四. 小结

最近比较忙碌,只能先借鉴别人的代码进行学习,后续要深入研究。

leetcode笔记:Combination Sum

原文:http://blog.csdn.net/liyuefeilong/article/details/50044961

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!