341. Flatten Nested List Iterator: 用递归的方法把值先全部expand,或者在hasnext中expand出一个integer,判断出stack的第一个值时integer的时候就返回true
343. Integer Break: dp问题,注意前几个case,也就是说当分解后的乘积小于自身的时候要取自身的值
347.\ Top K Frequent Elements: 用heap自然可以直接做,但是如果在followup里,可以用bucketsortbucketsort的想法就是把同一性质的数放到同一个bucket里。这里是把具有同样frequency的数(先做hash,count frequency)放到bucket里bucket[index] -> list然后由高位到低位依次数。
348. Design Tic-Tac-Toe: 这题还算是简单,主要是减少记录的信息,不需要记录整个棋盘,只要在每下一步,记录一下行,列,对角线,反对角线的个数就好了。
351. Android Unlock Patterns: 一道backtracking的题目,其中的状态变化是从某个按键,能否移动到下一个按键。
class Solution(object):
def numberOfPatterns(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
skip = [[0 for _ in range(10)] for _ in range(10)]
skip[1][3] = skip[3][1] = 2
skip[1][7] = skip[7][1] = 4
skip[3][9] = skip[9][3] = 6
skip[7][9] = skip[9][7] = 8
skip[1][9] = skip[9][1] = skip[2][8] = skip[8][2] = skip[3][7] = skip[7][3] = skip[4][6] = skip[6][4] = 5
vis = [False]*10
rst = 0;
# DFS search each length from m to n
for i in range(m, n+1):
rst += self.dfs(vis, skip, 1, i - 1) * 4; # 1, 3, 7, 9 are symmetric
rst += self.dfs(vis, skip, 2, i - 1) * 4; # 2, 4, 6, 8 are symmetric
rst += self.dfs(vis, skip, 5, i - 1) # 5
return rst
def dfs(self, vis, skip, cur, remain):
if remain < 0:
return 0
if remain == 0:
return 1
vis[cur] = True
rst = 0
for i in range(1, 10):
# If vis[i] is not visited and (two numbers are adjacent or skip number is already visited)
if not vis[i] and (skip[cur][i] == 0 or vis[skip[cur][i]]):
rst += self.dfs(vis, skip, i, remain - 1)
vis[cur] = False
return rst
353. Design Snake Game: 这种设计题不难,但是要用最精简的数据结构来构造最合适的,还是不容易的,可能会设计出不少冗余出来。
355. Design Twitter:getfeeds 有点类似first k element in n sorted linkedlist,用heap来做
356. Line Reflection:先按照y值进行hash,然后先对第一个key找它的reflect line,然后对后面所有的值验证一下reflect line
357. Count Numbers with Unique Digits:比较简单的一道dp题,推导公式为dp[i] = dp[i-1] * (10-i+1)
360. Sort Transformed Array:先对整个arr进行数学运算,然后从两头依次找就可以了。只是要注意a的取值,a是正负或者是0