class Solution(object):
def tribonacci(self, n):
"""
:type n: int
:rtype: int
"""
t0, t1, t2 = 0, 1, 1
if n == 0: return t0
if n == 1: return t1
if n == 2: return t2
for i in range(n - 2):
t0, t1, t2 = t1, t2, t0 + t1 + t2
return t2
board = ["abcde",
"fghij",
"klmno",
"pqrst",
"uvwxy",
"z"]
初始位置为 ( 0 , 0 ) (0,0) (0,0), U / D / L / R U / D / L / R U/D/L/R 分别代表向 上 / 下 / 左 / 右 上 / 下 / 左 / 右 上/下/左/右 前进一步, ! ! !代表保存当前位置的字符,要求给定一段字符串 t a r g e t target target, 按照查询数组依次获取 t a r g e t target target 的字符,并返回最小行走方案(可能存在多种,返回一种即可)。
class Solution(object):
def alphabetBoardPath(self, target):
"""
:type target: str
:rtype: str
"""
board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"]
_dict = {}
for i in range(len(board)):
for j in range(len(board[i])):
_dict[board[i][j]] = (i, j)
curr = (0, 0)
ans = ""
for c in target:
dst = _dict[c]
U = max(0, curr[0] - dst[0])
D = max(0, dst[0] - curr[0])
L = max(0, curr[1] - dst[1])
R = max(0, dst[1] - curr[1])
ans += "U"*U + "D"*D + "L"*L + "R"*R
ans += "!"
curr = dst
return ans
class Solution(object):
def largest1BorderedSquare(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
l1, l2 = len(grid), len(grid[0])
top, left = [x[:] for x in grid], [x[:] for x in grid]
for i in range(l1):
for j in range(l2):
if grid[i][j] and i > 0:
top[i][j] = top[i - 1][j] + 1
if grid[i][j] and j > 0:
left[i][j] = left[i][j - 1] + 1
for r in range(min(l1, l2), 0, -1):
for i in range(l1 - r + 1):
for j in range(l2 - r + 1):
if top[i + r - 1][j + r - 1] >= r and top[i + r - 1][j] >= r \
and left[i + r - 1][j + r - 1] >= r and left[i][j + r - 1] >= r:
return r * r
return 0
from collections import defaultdict
class Solution(object):
def stoneGameII(self, piles):
"""
:type piles: List[int]
:rtype: int
"""
bp = defaultdict(lambda:-1)
def dfs(remains, M):
if bp[(len(remains), M)] != -1: return bp[(len(remains), M)]
if len(remains) <= 2*M: return sum(remains)
ans = 0
for X in range(1, 2*M + 1):
ans = max(sum(remains[:X]) + sum(remains[X:]) - dfs(remains[X:], max(M, X)), ans)
bp[(len(remains), M)] = ans
return ans
return dfs(piles, 1)