题目1
题解1
class Solution:
"""
1. 子问题: DP[i] 到第i元素最多的爬取方式
2. 子方法之间的关系:
第 i 阶可以由以下两种方法得到:
在第 (i-1)阶后向上爬1阶。
在第 (i-2)阶后向上爬2阶
DP[i] = DP[i-1] + DP[i-2]
3. 起始条件: DP[0] = 0
DP[1] = 1
DP[2] = 2
4. 画表:
i 0 1 2 3 4 5
num 1 2 3 4 5
DP 0 1 2 3 5 8
"""
def climbStairs(self, n: int) -> int:
if n < 3:
return n
DP = [None] * (n+1)
DP[1] = 1
DP[2] = 2
for i in range(3, n+1):
DP[i] = DP[i-1] + DP[i-2]
return DP[-1]
题目2
题解2
class Solution:
def mySqrt(self, x: int) -> int:
if x < 2:
return x
for i in range(1,x+1):
if x//i < i:
return i -1
题目3
题解3
class Solution:
def addBinary(self, a: str, b: str) -> str:
"""
1. 把 aa 和 bb 转换成整型数字 xx 和 yy,xx 保存结果,yy 保存进位。
2. 当进位不为 0:y != 0:
3. 计算当前 xx 和 yy 的无进位相加结果:answer = x^y。
4. 计算当前 xx 和 yy 的进位:carry = (x & y) << 1。
5. 完成本次循环,更新 x = answer,y = carry。
6. 返回 xx 的二进制形式。
"""
x, y = int(a, 2), int(b, 2)
while y:
x, y = x ^ y, (x & y) << 1
return bin(x)[2:]