leetcode小白刷题之旅----39. Combination Sum
仅供自己学习
题目:
Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.
The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.
It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input.
Example 1:
Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Explanation:
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.
Example 2:
Input: candidates = [2,3,5], target = 8
Output: [[2,2,2,2],[2,3,3],[3,5]]
Example 3:
Input: candidates = [2], target = 1
Output: []
Example 4:
Input: candidates = [1], target = 1
Output: [[1]]
Example 5:
Input: candidates = [1], target = 2
Output: [[1,1]]
思路:
考虑到要再数组里面找到和能等于target的数,则要遍历所有的数,考虑用回朔法。因为并不能准确知道哪些之和能等于target所以只能每个数都加进来试试,不满足回朔时再把该数删除掉。又因为题目允许重复取数,所以每次递归的开始都从该数开始。我们用一个out存放一种可行的combination sum,当sum = target后就将其加入到 res数组。
这种方法会存在重复的结果导致时间消耗过多,可引入一些剪枝的方法或自底向上的动态规划方法。但是我不会所以就只记录这种暴力搜索的方法了。
代码:
1 class Solution { 2 public: 3 vector<vector<int>> combinationSum(vector<int>& candidates, int target) { 4 int sum=0; 5 vector<vector<int> > res; 6 vector<int> out; 7 backtracking(target,sum,candidates,out,res,0); 8 return res; 9 } 10 void backtracking(int target,int sum,vector<int>& candidates,vector<int> out,vector<vector<int> >& res,int start){ 11 if(sum == target){ 12 res.push_back(out); 13 return; 14 } 15 if(sum>target) return; 16 for(int i=start;i<candidates.size();i++){ 17 sum+=candidates[i]; 18 out.push_back(candidates[i]); 19 backtracking(target,sum,candidates,out,res,i); 20 out.pop_back(); 21 sum -= candidates[i]; 22 } 23 } 24 };