一 网站建设方案,1元建网站,门户网站信息流广告怎么做,网站框架是怎么做的一#xff1a;题目#xff1a;
给定一个无重复元素的正整数数组 candidates 和一个正整数 target #xff0c;找出 candidates 中所有可以使数字和为目标数 target 的唯一组合。
candidates 中的数字可以无限制重复被选取。如果至少一个所选数字数量不同#xff0c;则两种…一题目
给定一个无重复元素的正整数数组 candidates 和一个正整数 target 找出 candidates 中所有可以使数字和为目标数 target 的唯一组合。
candidates 中的数字可以无限制重复被选取。如果至少一个所选数字数量不同则两种组合是唯一的。
对于给定的输入保证和为 target 的唯一组合数少于 150 个。
示例 1输入: candidates [2,3,6,7], target 7
输出: [[7],[2,2,3]]
示例 2输入: candidates [2,3,5], target 8
输出: [[2,2,2,2],[2,3,3],[3,5]]
示例 3输入: candidates [2], target 1
输出: []
示例 4输入: candidates [1], target 1
输出: [[1]]
示例 5输入: candidates [1], target 2
输出: [[1,1]]二思路
思路 1:递归函数的递归参数为 backtacking(vector v,int target); 2:递归的结果 vectorvector ans;//装入所有的可行解 vector path;每次递归将一个值装入容器中 3:递归终止条件 accumulate(path.begin(),path.end(),0) target
4:单层横向的for循环为遍历容器的元素纵向为递归深度
三:上码
class Solution {
public:vectorvectorint ans;vectorintpath;void backtacking(vectorint v,int num,int index){int sum accumulate(path.begin(),path.end(),0);if(sum num){return ;}if(sum num){ans.push_back(path);return ;}for(int i index; i v.size(); i){path.push_back(v[i]);backtacking(v,num,i);//这里加上index可以避免重复path.pop_back();}}vectorvectorint combinationSum(vectorint candidates, int target) {/**思路1:递归函数的递归参数为backtacking(vectorint v,int target);2:递归的结果vectorvectorint ans;//装入所有的可行解vectorint path;每次递归将一个值装入容器中3:递归终止条件accumulate(path.begin(),path.end(),0) target4:单层横向的for循环为遍历容器的元素纵向为递归深度 */backtacking(candidates,target,0);return ans;}
};加油 宝