Unique Binary Search Trees Problem
Given n, how many structurally unique BSTs (binary search trees) that store values 1...n?
ExampleGiven n = 3, there are a total of 5 unique BST"s.
1 3 3 2 1 / / / 3 2 1 1 3 2 / / 2 1 2 3Note
DP
Solutionpublic class Solution { public int numTrees(int n) { int[] count = new int[n+1]; count[0] = 1; for (int i = 1; i <= n; i++) { for (int root = 1; root <= i; root++) { int left = count[root-1]; int right = count[i-root]; count[i] += left*right; } } return count[n]; } }Unique Binary Search Trees II Problem
Given n, generate all structurally unique BST"s (binary search trees) that store values 1...n.
ExampleGiven n = 3, your program should return all 5 unique BST"s shown below.
1 3 3 2 1 / / / 3 2 1 1 3 2 / / 2 1 2 3Note
DFS
Solutionclass Solution { public ListgenerateTrees(int n) { if (n == 0) return new ArrayList<>(); return helper(1, n); } private List helper(int start, int end) { List res = new ArrayList<>(); if (start > end) { res.add(null); return res; } for (int i = start; i <= end; i++) { List left = helper(start, i-1); List right = helper(i+1, end); for (TreeNode leftNode: left) { for (TreeNode rightNode: right) { TreeNode root = new TreeNode(i); root.left = leftNode; root.right = rightNode; res.add(root); } } } return res; } }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://specialneedsforspecialkids.com/yun/65702.html
摘要:在這里我們使用數(shù)組中下標(biāo)為的位置來記錄個(gè)元素可以組成的平衡二叉樹的數(shù)量。在遞歸的過程中,我們找到以當(dāng)前節(jié)點(diǎn)作為根節(jié)點(diǎn)的所有平衡二叉樹,并將結(jié)果以形式返回上一級(jí)調(diào)用。 題目要求 Given n, how many structurally unique BSTs (binary search trees) that store values 1...n? For example, Gi...
摘要:而根可以選擇從到的任意的數(shù),唯一二叉樹的總數(shù),就是根為到的樹相加。所以該問題化簡(jiǎn)為以為根,其唯一左子樹和右子樹各有多少,這就是個(gè)動(dòng)態(tài)規(guī)劃的問題了。 Unique Binary Search Trees I && II 解法請(qǐng)見:https://yanjia.li/zh/2019/02/... Given n, how many structurally unique BSTs (b...
摘要:題目解讀窮舉列出所有二叉樹的結(jié)構(gòu)類型。重點(diǎn)動(dòng)態(tài)規(guī)劃,關(guān)注臨近,,之間的關(guān)系應(yīng)用窮舉組合,動(dòng)態(tài)規(guī)劃窮舉組合,適用于相鄰元素有規(guī)律。處注意邊界值的情況。不能有重復(fù),遺漏。 題目解讀: 窮舉列出所有二叉樹的結(jié)構(gòu)類型。重點(diǎn): 動(dòng)態(tài)規(guī)劃,關(guān)注臨近root,left,right之間的關(guān)系應(yīng)用:窮舉組合,動(dòng)態(tài)規(guī)劃窮舉組合,適用于相鄰元素有規(guī)律。bug處:注意邊界值的情況。不能有重復(fù),遺漏。 clas...
Unique Binary Search TreesGiven n, how many structurally unique BSTs (binary search trees) that store values 1...n? For example,Given n = 3, there are a total of 5 unique BSTs. 1 3 3 ...
摘要:在線網(wǎng)站地址我的微信公眾號(hào)完整題目列表從年月日起,每天更新一題,順序從易到難,目前已更新個(gè)題。這是項(xiàng)目地址歡迎一起交流學(xué)習(xí)。 這篇文章記錄我練習(xí)的 LeetCode 題目,語言 JavaScript。 在線網(wǎng)站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公眾號(hào): showImg(htt...
閱讀 3980·2021-11-23 10:09
閱讀 1344·2021-11-23 09:51
閱讀 2944·2021-11-23 09:51
閱讀 1590·2021-09-07 09:59
閱讀 2357·2019-08-30 15:55
閱讀 2301·2019-08-30 15:55
閱讀 2953·2019-08-30 15:52
閱讀 2565·2019-08-26 17:04