题目链接:点击打开链接
题目大意:略
解题思路:解决方案(1) & 解决方案(2) 的区别在于 list.add & list.remove 的时机,只要能前后对称起来即可
相关企业
- 美团
- 字节跳动
- 亚马逊(Amazon)
- 谷歌(Google)
- 微软(Microsoft)
- 甲骨文(Oracle)
AC 代码
- Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ // 解决方案(1) class Solution { LinkedList<List<Integer>> res = new LinkedList<>(); LinkedList<Integer> path = new LinkedList<>(); public List<List<Integer>> pathSum(TreeNode root, int sum) { recur(root, sum); return res; } void recur(TreeNode root, int tar) { if(root == null) return; path.add(root.val); tar -= root.val; if(tar == 0 && root.left == null && root.right == null) res.add(new LinkedList(path)); recur(root.left, tar); recur(root.right, tar); path.removeLast(); } } // 解决方案(2) class Solution { private int target; private List<List<Integer>> list; private List<Integer> subList; public List<List<Integer>> pathSum(TreeNode root, int target) { this.target = target; list = new ArrayList<>(); subList = new ArrayList<>(); dfs(root, 0); return list; } private void dfs(TreeNode node, int sum) { if (null == node) { // 为了配合演出回溯的 remove, 否则会导致删除和新增不一致 subList.add(null); return; } sum += node.val; subList.add(node.val); if (null == node.right && null == node.left) { if (sum == target) { list.add(new ArrayList<>(subList)); } return; } dfs(node.left, sum); subList.remove(subList.size() - 1); dfs(node.right, sum); subList.remove(subList.size() - 1); } }
- C++
/** * 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 sum) { recur(root, sum); return res; } private: vector<vector<int>> res; vector<int> path; void recur(TreeNode* root, int tar) { if(root == nullptr) return; path.push_back(root->val); tar -= root->val; if(tar == 0 && root->left == nullptr && root->right == nullptr) res.push_back(path); recur(root->left, tar); recur(root->right, tar); path.pop_back(); } };