leetcode中的递归调用总结
2017-05-25 10:02
232 查看
只是总结我在刷leetcode过程中遇到的使用递归来解决的问题
437. Path Sum III
You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000
代码:
78. Subsets
Given a set of distinct integers, nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
For example,
If nums =
437. Path Sum III
You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8 10 / \ 5 -3 / \ \ 3 2 11 / \ \ 3 -2 1 Return 3. The paths that sum to 8 are: 1. 5 -> 3 2. 5 -> 2 -> 1 3. -3 -> 11
代码:
class Solution { public: int pathSum(TreeNode* root, int sum) { if(!root) return 0; return sumUp(root, 0, sum) + pathSum(root->left, sum) + pathSum(root->right, sum); } private: int sumUp(TreeNode* root, int pre, int& sum){ if(!root) return 0; int current = pre + root->val; return (current == sum) + sumUp(root->left, current, sum) + sumUp(root->right, current, sum); } };
78. Subsets
Given a set of distinct integers, nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
For example,
If nums =
[1,2,3], a solution is:
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
class Solution { public: vector<vector<int>> subsets(vector<int>& nums) { sort(nums.begin(), nums.end()); vector<vector<int>> subs; vector<int> sub; genSubsets(nums, 0, sub, subs); return subs; } void genSubsets(vector<int>& nums, int start, vector<int>& sub, vector<vector<int>>& subs) { subs.push_back(sub); for (int i = start; i < nums.size(); i++) { sub.push_back(nums[i]); genSubsets(nums, i + 1, sub, subs); sub.pop_back(); } } };
相关文章推荐
- LeetCode总结,递归的理解与设计
- 算法总结(7)--leetcode上的递归,BFS,DFS思考
- 算法小白总结(二)------递归调用
- java基础,递归调用的初学总结
- leetcode 求最大深度 之 递归 总结
- Leetcode 递归知识点总结
- 递归调用与时间复杂度的学习总结
- leetcode -- 解题总结--DP与DFS, 递归
- 递归调用总结
- netfilter各个HOOK的关系简介(笔记中已经总结到函数调用流程中)
- Js 调用 WebService心得总结
- [总结]利用Javascript 调用WebService
- Js 调用 WebService心得总结
- Js 调用 WebService心得总结
- 现实中的递归调用!!!
- 小问题,对递归重复调用的改进,一起来分享
- 关于java调用window DLL里的函数的总结
- 在.NET中调用Oracle9i存储过程经验总结
- 字节对齐和C/C++函数调用方式学习总结(多篇节选)
- .net中调用com的具体操作(总结)