Leet Code -- Unique BST】的更多相关文章

对于数字n(大于1).从1到n有多少种binary search tree(BST序列)?当n=3时,BST序列为: 1         3     3    2     1     \         /     /      / \      \     3      2    1    1  3     2     /       /       \                  \   2      1         2                3共5种. 分析: N=1时,…
描述: 使用了递归,有些计算是重复的,用了额外的空间,Version 1是m*n Bonus:一共走了m+n步,例如 m = 2, n = 3 [#, @, @, #, @],所以抽象成数学问题,解是C(m + n, m) 代码: class Solution: # @return an integer def __init__(self): self.record = {} def uniquePaths(self, m, n): if m == 0 or n == 0: return 0 i…
语言:Python 描述:使用递归实现 class Solution: # @return an integer def numTrees(self, n): : elif n == : else: part_1 = self.numTrees(n-) * part_2 = ,n-): part_left = self.numTrees(i) part_right = self.numTrees(n - - i) part_2 += part_left * part_right return p…
Palindrome Number Total Accepted: 19369 Total Submissions: 66673My Submissions Determine whether an integer is a palindrome. Do this without extra space. 推断一个数整数是不是回文?比如121,1221就是回文,好吧,直接利用前面写过的[Leet Code]Reverse Integer--"%"你真的懂吗? 只是这里要考虑翻转后,数值…
Leet Code编程题 希望能从现在开始,有空就做一些题,自己的编程能力太差了. 771 宝石与石头 简单题 应该用集合来做 给定字符串J 代表石头中宝石的类型,和字符串 S代表你拥有的石头. S 中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的石头中有多少是宝石. J 中的字母不重复,J 和 S中的所有字符都是字母.字母区分大小写,因此"a"和"A"是不同类型的石头. 示例 1: 输入: J = "aA", S = "aAA…
描述: 要求相邻数2进制差一位 先获得n-1的列表表示小于 2^(n-1) 的符合要求的列表,加上最高位的加成 2^(n-1) 就是大于等于 2^(n-1) 的符合要求的列表,后者翻转一下就能够与前者连接上了 代码: class Solution: # @return a list of integers def grayCode(self, n): if n == 0: return [0] s1 = self.grayCode(n - 1) s2 = [item + 2 ** (n - 1)…
描述: 输出全排列 代码: class Solution: # @param num, a list of integer # @return a list of lists of integers def doSth(self, num): result = self.permute(num[1:]) for lst in result: for i in range(len(lst) + 1): yield lst[:i] + num[:1] + lst[i:] def permute(se…
描述:注意需要先self.connect(right)再self.connect(left),否则会有case通不过,原因是左边递归执行时依赖与右边的next已经建立,而先执行connect(left)的话右边还没有完成关系的建立. 代码: class Solution: # @param root, a tree node # @return nothing def doSth(self, nextNode, conNode): while nextNode is not None: if n…
描述:log(n) 代码: class Solution: # @param x, an integer # @return an integer def getVal(self, begin, end, x): if end == begin : return begin if end == begin + 1: return begin while True: mid = (begin + end) / 2 tmp = mid * mid if tmp == x: return mid el…
描述:数组 A,对于 i < j, 找到最大的 A[j] - A[i] 代码: class Solution: # @param prices, a list of integer # @return an integer def maxProfit(self, prices): if len(prices) == 0 or len(prices) == 1: return 0 cur_min = prices[0] max_minus = 0 for i in range(1, len(pri…
描述:递归 代码: class Solution: # @param num, a list of integers # @return a tree node def sortedArrayToBST(self, num): if len(num) == 0: return None mid_index = len(num) / 2 tmp_tree = TreeNode(num[mid_index]) tmp_tree.left = self.sortedArrayToBST(num[:mi…
描述:计算逆波兰表达法的结果 Sample: [", "*"] -> ((2 + 1) * 3) -> 9 [", "/", "+"] -> (4 + (13 / 5)) -> 6 使用stack实现: def is_op(c): return c in ['+', '-', '*', '/'] def divide(x, y): if (x * y) < 0: return -1 * ((-x)…
描述:递归调用,getMax返回 [节点值,经过节点左子节点的最大值,经过节点右节点的最大值],每次递归同时查看是否存在不经过节点的值大于max. 代码:待优化 def getLargeNode(self, a, b): if a and b: return max(a, b) elif a and not b: return a elif not a and b: return b else: tmp = None def getMax(self, node): if node is None…
描述:不使用 * / % 完成除法操作.O(n)复杂度会超时,需要O(lg(n))复杂度. 代码: class Solution: # @return an integer def dividePositive(self, dividend, divisor): if dividend < divisor: return 0 sum = divisor count = 1 while sum + sum < dividend: sum += sum count += count count +…
语言:Python 描述:使用递归实现 def getList(self, node): if node is None: return [] if node.left is None and node.right is None: return [[node.val]] result = [] for item in self.getList(node.left): result.append([node.val] + item) for item in self.getList(node.r…
语言:Python 描述:使用递归实现 # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param p, a tree node # @param q, a tree node # @return a boolean def isSameTre…
语言:C++ 描述:使用单链表实现,HeadNode是key=-1,value=-1,next=NULL的结点.距离HeadNode近的结点是使用频度最小的Node. struct Node { int key; int value; Node* next; }; class LRUCache { public: LRUCache(int capacity) { this->capacity = capacity; ; this->headNode = new Node(); ; ; this…
;            ;                ;                            }        }        ;            }};…
问题叙述性说明: Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index. For exa…
Given a string, find the length of the longest substring without repeating characters. Examples: Given "abcabcbb", the answer is "abc", which the length is 3. Given "bbbbb", the answer is "b", with the length of 1.…
1 题目 Given two binary trees, write a function to check if they are equal or not. Two binary trees are considered equal if they are structurally identical and the nodes have the same value. Hide Tags Tree Depth-first Search   2 思路 好久没做树的题目了,选了一道最简单的树的…
1 题目 You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. Input: (2 -> 4 -> 3) + (5 -> 6 -…
1 题目 You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will…
1 题目 Reverse bits of a given 32 bits unsigned integer. For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000). Follow up:If this funct…
1 题目 Compare two version numbers version1 and version2.If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0. You may assume that the version strings are non-empty and contain only digits and the . character.The . cha…
1 题目 There are N children standing in a line. Each child is assigned a rating value. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy. Children with a higher rating get more can…
1 题目 There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). 2 思路 这题比较简单,实现的其实就是归并排序merge那个部分. 3 代码 public class MedianOfTwoSortedArrays { pub…
此题如果 #1 和 #4 判断分支交换,大集合就会超时(因为每次对于非叶子节点都要判断是不是叶子节点).可见,有时候if else判断语句也会对于运行时间有较大的影响. import java.util.ArrayList; class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public class Solution { private int currSum = 0;…
很简单一道题,搞错了N次,记录一下. public class Solution { private int currSum = 0; public boolean hasPathSum(TreeNode root, int sum) { if (null == root) return false; currSum = 0; return hasPathSumCore(root, sum); } public boolean hasPathSumCore(TreeNode root, int…
题目: Invert a binary tree. 4 / \ 2 7 / \ / \ 1 3 6 9 to 4 / \ 7 2 / \ / \ 9 6 3 1 思路分析: 题意是将二叉树全部左右子数对调,如上图所看到的. 详细做法是,先递归处理左右子树,然后将当前的左右子树对调. 代码实现: /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeN…