无序数组返回两个元素和为给定值的下标. tricks:无序.返回下标增序.返回的是原始数组的下标. vector<int>*pa; bool cmp(int x,int y){ return (*pa)[x]<(*pa)[y]; } class Solution { public: vector<int> twoSum(vector<int> &a, int t) { int n=a.size(); pa=&a; int* id=new int[n…
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. For example:Given the below binary tree and sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1 return [ [5,4,11,2], [5,8,4,5] ] 这道二叉树路径之和在之前的基础上又需要找…
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. 通过一个p指针,遍历 二叉树,并将每次的值 保存在 sum2 中 . 遇到右节点,将右节点+depth 保存在 temp中,当再次使用 该节点时,根据depth 将sum2中的长度削减成 depth-1 /** * Definition for a binary tree node. * st…
LeetCode:Path Sum Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example:Given the below binary tree and sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ \…
https://oj.leetcode.com/problems/path-sum-ii/ 树的深搜,从根到叶子,并记录符合条件的路径. 注意参数的传递,是否需要使用引用. #include <iostream> #include <vector> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL),…
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers. For example, 1 / \ 2 3…
Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times. Note: All numbers (including target) will…
题意: 给一棵二叉树,每个叶子到根的路径之和为sum的,将所有可能的路径装进vector返回. 思路: 节点的值可能为负的.这样子就必须到了叶节点才能判断,而不能中途进行剪枝. /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL)…
要求给定树,与路径和,判断是否存在从跟到叶子之和为给定值的路径.比如下图中,给定路径之和为22,存在路径<5,4,11,2>,因此返回true;否则返回false. 5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 5思路递归,从跟到叶子判断,如果在叶子处剩下的给定值恰好为给定值,那么返回ture.参考代码 /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * T…
题目 题目 思路 一看就是单点更新和区间求和,故用线段树做. 一开始没搞清楚,题目给定的i是从0开始还是从1开始,还以为是从1开始,导致后面把下标都改掉了,还有用区间更新的代码去实现单点更新,虽然两者思路是一样的,但是导致TLE,因为区间会把所有都递归一遍,加了个判断,就ok了. if (idx <= middle) { this->updateHelper(curIdx << 1, leftIdx, middle, idx, val); } else { this->upd…