1、牛客网 NC46 加起来和为目标值的组合
class Solution {
public:
void dfs(vector<vector<int>>&res,vector<int>&path,vector<int>&num,int cur,int target){
if(target==0){
res.push_back(path);
return;
}
if(cur>=num.size()) return;
for(int i=cur;i<num.size();i++){
if(i>cur&&num[i]==num[i-1]) continue;
if(num[i]<=target){
path.push_back(num[i]);
dfs(res,path,num,i+1,target-num[i]);
path.pop_back();
}
}
}
vector<vector<int> > combinationSum2(vector<int> &num, int target) {
sort(num.begin(),num.end());
vector<vector<int>>res;
vector<int>path;
if(num.size()<1) return res;
dfs(res,path,num,0,target);
return res;
}
};
2、leetcode 560 和为K的子数组
给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
unordered_map<int,int>mp;
mp[0]=1;
int count=0,pre=0;
for(auto x:nums){
pre+=x;
if(mp.find(pre-k)!=mp.end()){
count+=mp[pre-k];
}
mp[pre]++;
}
return count;
}
};
3、剑指 Offer 34. 二叉树中和为某一值的路径
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int target) {
vector<vector<int>>res;
vector<int>path;
dfs(res,path,root,target);
return res;
}
void dfs(vector<vector<int>>&res,vector<int>&path,TreeNode* root,int target){
if(!root) return;
path.push_back(root->val);
if(root->left==NULL&&root->right==NULL&&target-root->val==0){
res.push_back(path);
}
dfs(res,path,root->left,target-root->val);
dfs(res,path,root->right,target-root->val);
path.pop_back();
}
};