63. Unique Paths II
https://leetcode.com/problems/unique-paths-ii/description/
class Solution(object):
def uniquePathsWithObstacles(self, obstacleGrid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
m = len(obstacleGrid)
n = len(obstacleGrid[0])
path = [[0 for a in range(n)] for b in range(m)]
for i in range(m):
if (obstacleGrid[i][0] == 1):
break
path[i][0] = 1
for i in range(n):
if (obstacleGrid[0][i] == 1):
break
path[0][i] = 1
for i in range(1, m):
for j in range(1, n):
if (obstacleGrid[i][j] == 1):
path[i][j] = 0
else:
path[i][j] = path[i - 1][j] + path[i][j - 1]
return path[m - 1][n - 1]
104. Maximum Depth of Binary Tree
https://leetcode.com/problems/maximum-depth-of-binary-tree/description/
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None:
return 0
else:
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
222. Count Complete Tree Nodes
https://leetcode.com/problems/count-complete-tree-nodes/description/
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def countNodes(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if (root == None):
return 0
path = []
while (root != None):
if root.left == None and root.right == None:
break
if self.depth(root.left) > self.depth(root.right):
root = root.left
path.append(0)
else:
root = root.right
path.append(1)
l = len(path)
index = 0
for i, p in enumerate(path):
if p == 1:
index += 2 ** (l - i -1)
num = 2 ** len(path) + index
return num
def depth(self, root):
tmp = root
max_depth = 0
while (tmp != None):
max_depth += 1
tmp = tmp.left
return max_depth
476. Number Complement
https://leetcode.com/problems/number-complement/#/description
public class Solution {
public int findComplement(int num) {
String s = Integer.toBinaryString(num);
int ret = 0;
for (int i = 0; i < s.length(); i ++) {
if (s.charAt(i) == '0') {
ret += Math.pow(2, s.length() - i - 1);
}
}
return ret;
}
}
492. Construct the Rectangle
https://leetcode.com/problems/construct-the-rectangle/#/description
public class Solution {
public int[] constructRectangle(int area) {
int []ret = {0, 0};
int L, W;
for (W = 1; W <= Math.pow(area, 0.5); W ++) {
L = area / W;
if (L * W == area) {
ret[0] = L;
ret[1] = W;
}
}
return ret;
}
}