Leetcode: 39. Combination Sum(Week12, Medium)

来源:互联网 发布:手机文本加密软件 编辑:程序博客网 时间:2024/04/29 17:10

Leetcode39:
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]
]

  • 题意:现有一个数字序列和一个目标值,要求从数字序列中找到所有组合(组合不能哟重复),使得该组合的和等于该目标值。
  • 思路:凡是要求出所有组合方式的题目,大多数都可以采用递归的思想求解。
  • 代码如下:
class Solution {public:    vector<vector<int> > combinationSum(vector<int>& candidates, int target) {        sort(candidates.begin(), candidates.end());        vector<vector<int> > result;        vector<int> temp_result;        solve_Combination_Sum(candidates, result, temp_result, target, 0);        return result;    }    void solve_Combination_Sum(vector<int>& candidates, vector<vector<int> >& result, vector<int>& out, int target, int index) {        if (target < 0) return;        if (target == 0) {            result.push_back(out);        }        for (int i = index; i < candidates.size(); i++) {            out.push_back(candidates[i]);            solve_Combination_Sum(candidates, result, out, target-candidates[i], i);            out.pop_back();        }    }   };

以上内容结尾本人观点,欢迎大家提出批评和指导,我们一起探讨!