不准发言
- 积分
- 38
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2018-7-10
- 最后登录
- 1970-1-1
|
- /**
- * Definition for a binary tree node.
- * struct TreeNode {
- * int val;
- * TreeNode *left;
- * TreeNode *right;
- * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
- * };
- */
- class Solution {
- public:
- void helper(TreeNode* root, int sum, map<int, vector<vector<int>>> pathSum, int curr_sum, vector<int> curr_path, int& numOfPath, vector<vector<int>>& paths) {
- if (!root) {
- return;
- }
- curr_sum += root->val;
- if (pathSum.count(curr_sum - sum)) {
- numOfPath += pathSum[curr_sum - sum].size();
- for (auto i:pathSum[curr_sum - sum]) {
- vector<int> temp;
- for (int cnt = i.size(); cnt < curr_path.size(); cnt++) {
- temp.push_back(curr_path[cnt]);
- }
- temp.push_back(root->val);
- paths.push_back(temp);
- }
- }
- curr_path.push_back(root->val);
- pathSum[curr_sum].push_back(curr_path);
-
- helper(root->left, sum, pathSum, curr_sum, curr_path, numOfPath, paths);
- helper(root->right, sum, pathSum, curr_sum, curr_path, numOfPath, paths);
- }
- int pathSum(TreeNode* root, int sum) {
- int numOfPath = 0;
- map<int, vector<vector<int>>> pathSum;
- pathSum[0].push_back(vector<int>());
- vector<int> cur_path;
- vector<vector<int>> paths;
- helper(root, sum, pathSum, 0, cur_path, numOfPath, paths);
- for (auto i:paths) {
- for (auto j:i) cout << j << " -> ";
- cout << endl;
- }
- return numOfPath;
- }
- };
复制代码
及其耗空间的解法 不过如果时间只有45min 我也只能想到这样了 用lc437测了下 应该是对的 |
|