递归

来源:互联网 发布:java物流项目简历 编辑:程序博客网 时间:2024/05/22 00:22
题目:

Given a set of candidate numbers (C(without duplicates) 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]]

题目解析:此题要求我们在向量集合中求出元素相加等于所给目标数的组合,属于中等难度的题目;在这里我们首先将集合进行排序,再写一个判断组合的函数,用一个for循环从最小的数开始判断,循环条件要注意i不能大于向量大小以及第i个元素不能大于目标数;在循环中调用递归遍历所有的元素,之后再回溯即可。


程序如下:

class Solution {
public:
        vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        sort(candidates.begin(), candidates.end());
        vector<vector<int> > res;
        vector<int> combination;
        combinationSum(candidates, target, res, combination, 0);
        return res;
    }
private:
    void combinationSum(vector<int> &candidates, int target, vector<vector<int> > &res, vector<int> &combination, int begin) {
        if (!target) {
            res.push_back(combination);
            return;
        }
        for (int i = begin; i != candidates.size() && target >= candidates[i]; ++i) {
            combination.push_back(candidates[i]);
            combinationSum(candidates, target - candidates[i], res, combination, i);
            combination.pop_back();
        }
    }
};





0 0
原创粉丝点击