LeetCode練習-中等卷
題目連結:LeetCode練習-中等卷。
1、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
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Return the sum = 12 + 13 =25.
分析:先序遍歷的思想(根左右)+數字求和(每一層都比上層和*10+當前根節點的值)。
<span style="font-size:18px;">/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sumNumbers(TreeNode *root) {
return sumdfs(root,0);
}
int sumdfs(TreeNode *root,int sum){
if(!root)
return 0;
sum = sum*10+root->val;
if(!root->left&&!root->right)
return sum;
return sumdfs(root->left,sum)+sumdfs(root->right,sum);
}
};</span>
2、Given two integers n and k,
return all possible combinations of k numbers out of 1 ... n.For
example,
If n = 4 and k = 2, a solution is:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
分析:回溯法。
相關文章
- 生物套卷練習記錄
- js解leetcode(32)-中等JSLeetCode
- 語文套卷練習記錄
- JAVA-LeetCode中等29兩數相除JavaLeetCode
- leetcode 593. Valid Square練習LeetCode
- leetcode 593. Valid Square 練習LeetCode
- LeetCode-5426、重新規劃路線-中等LeetCode
- LeetCode C++ 50. Pow(x, n)【Recursion】中等LeetCodeC++
- 【leetcode】LCP 19. 秋葉收藏集(UlBDOe)(DP)[中等]LeetCode
- 【LeetCode刷題(中等程度)】946. 驗證棧序列LeetCode
- LeetCode C++ 56. Merge Intervals【排序/陣列】中等LeetCodeC++排序陣列
- LeetCode: 1052. 愛生氣的書店老闆(中等)LeetCode
- leetcode:面試題 01.08. 零矩陣(陣列,中等)LeetCode面試題矩陣陣列
- LeetCode C++ 33. Search in Rotated Sorted Array【二分】中等LeetCodeC++
- [LeetCode 中等 動態規劃 ]221. 最大正方形LeetCode動態規劃
- 演算法練習--LeetCode--54. Spiral Matrix 100%演算法LeetCode
- LeetCode演算法練習——深度優先搜尋 DFSLeetCode演算法
- leetcode陣列練習題2:283. 移動零LeetCode陣列
- 習題試卷
- LeetCode C++ 1302. Deepest Leaves Sum【Tree/BFS/DFS】中等LeetCodeC++
- 【LeetCode刷題(中等程度)】662. 二叉樹最大寬度LeetCode二叉樹
- LeetCode C++ 376. Wiggle Subsequence【Dynamic Programming】中等LeetCodeC++
- LeetCode C++ 316. Remove Duplicate Letters【Stack/Greedy/String】中等LeetCodeC++REM
- 【10月打卡~Leetcode每日一題】18. 四數之和(難度:中等)LeetCode每日一題
- 新手練習:Python練習題目Python
- MYSQL練習1: DQL查詢練習MySql
- 演算法練習--LeetCode--29. Divide Two Integers: 100%演算法LeetCodeIDE
- Python練習-LeetCode 第1篇 順時針列印矩陣PythonLeetCode矩陣
- LeetCode C++ 劍指 Offer 64. 求1+2+…+n【Bit Manipulation】中等LeetCodeC++
- 【Leetcode 346/700】79. 單詞搜尋 【中等】【回溯深度搜尋JavaScript版】LeetCodeJavaScript
- sql 練習SQL
- MySQL練習MySql
- latex練習
- ddl練習
- MySQ練習
- leetcode-MySQL 練習題之- 超過經理收入的員工LeetCodeMySql
- 程式設計師進階之演算法練習:LeetCode專場程式設計師演算法LeetCode
- leetcode:462. 最少移動次數使陣列元素相等 II(數學,中等)LeetCode陣列