p131 求和为给定值的组合(leetcode 39)
Posted repinkply
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了p131 求和为给定值的组合(leetcode 39)相关的知识,希望对你有一定的参考价值。
一:解题思路
Time:O(n^(target/min)),Space:O(target/min) ,其中n为数组长度,min是数组中的最小值。
二:完整代码示例 (C++版和Java版)
C++:
class Solution { private: void comSum(vector<int>& nums, int start, int target, vector<int>& elem, vector<vector<int>>& result) { if (target == 0) { result.push_back(elem); return; } if (target < 0) return; for (int i = start; i < nums.size(); i++) { elem.push_back(nums[i]); comSum(nums,i,target-nums[i],elem,result); elem.pop_back(); } } public: vector<vector<int>> combinationSum(vector<int>& candidates, int target) { vector<int> elem; vector<vector<int>> result; comSum(candidates,0,target,elem,result); return result; } };
Java:
class Solution { private void comSum(int[] nums,int start,int target,List<Integer> elem,List<List<Integer>> result) { if(target==0) { result.add(new ArrayList<>(elem)); return; } if(target<0) return; for(int i=start;i<nums.length;i++) { elem.add(nums[i]); comSum(nums,i,target-nums[i],elem,result); elem.remove(elem.size()-1); } } public List<List<Integer>> combinationSum(int[] candidates, int target) { List<Integer> elem=new ArrayList<>(); List<List<Integer>> result=new ArrayList<>(); comSum(candidates,0,target,elem,result); return result; } }
以上是关于p131 求和为给定值的组合(leetcode 39)的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 39 Combination Sum(满足求和等于target的所有组合)
LeetCode 40 Combination Sum II(数组中求和等于target的所有组合)