class Solution:
def myPow(self, x: float, n: int) -> float:
# # 法一:超时
# res = 1
# if n > 0:
# for i in range(n):
# res *= x
# # 考虑n<0
# if n < 0:
# for i in range(abs(n)):
# res /= abs(x)
# return res
# 递归
def cal_result(x,n):
if n==1: return x
# 递归哦
num = cal_result(x, n//2)
if n % 2 == 0:
return num * num
else:
return num * num * x
if n==0: return 1
# 考虑n为负,则倒数
if n<0:
return 1/cal_result(x,-n)
return cal_result(x,n)
好难 有点想不明白
class Solution:
def deleteNode(self, head: ListNode, val: int) -> ListNode:
# 第一个val就是的时候,直接返回后面部分
if head.val == val: return head.next
pre = head
while pre.next and pre.next.val!=val:
pre = pre.next
if pre.next:
pre.next = pre.next.next
return head # not pre
class Solution:
def printNumbers(self, n: int) -> List[int]:
res = []
for i in range(1,10**n):
res.append(i)
return res
class Solution:
def hammingWeight(self, n: int) -> int:
# 法一:使用语言特性,不过输入的n是整数就不是二进制???
cnt=Counter(str(bin(n)))
return cnt['1']
# 法二:使用语言特性
return bin(n).count('1')
# 法三:按位与运算
res = 0
while n:
res += n&1
n >>= 1
return res
class Solution:
def cuttingRope(self, n: int) -> int:
if n <= 3 : return n-1
a, b = n//3, n%3
# math.pow() 时间复杂度低,但是有溢出
if b == 0: res = int(pow(3, a))
if b == 1: res = int(pow(3, a-1) * 4)
if b == 2: res = int(pow(3, a) * 2)
return res % 1000000007
class Solution:
def cuttingRope(self, n: int) -> int:
# 长度为n的绳子分m段 长度乘积最大
# 每段长度相同时 是最佳的; 分成三段 是最佳的
# 所以每段长度3 余数0则3的n次方 余1则有一段是4 余2则有一段是2
a, b = n//3, n%3
if n<=3 : return n-1
if b==0: return int(math.pow(3,a))
if b==1: return int(math.pow(3, a-1)*4)
if b==2: return int(math.pow(3, a)*2)
class Solution:
def movingCount(self, m: int, n: int, k: int) -> int:
def digital(x):
sumres = 0
while x:
sumres += x%10
x //= 10
return sumres
visited = set([(0,0)])
for i in range(m):
for j in range(n):
# 只要考虑上一个是从左边过来还是上面过来就好了
if digital(i)+digital(j)<=k and ((i-1,j) in visited or (i,j-1) in visited):
visited.add((i,j))
return len(visited)
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
def DFS(i, j, seen):
# 停止条件
if len(seen)==len(word):
return True
# 遍历周围四个区域,没有False,有则继续
for (x,y) in [(i-1,j), (i+1,j), (i,j-1), (i,j+1)]:
if 0<=x<row and 0<=y<column and (x,y) not in seen and board[x][y]==word[len(seen)]:
seen.add((x,y))
if DFS(x,y,seen):
return True
seen.remove((x,y))
return False
if word == []: return True
row, column = len(board), len(board[0])
for i in range(row):
for j in range(column):
# DFS + 剪枝
if board[i][j]==word[0] and DFS(i, j, {
(i,j)}):
return True
return False
class Solution:
def minArray(self, numbers: List[int]) -> int:
# 法一:递增嘛,遇到gap就是答案了
for i in range(len(numbers)-1):
if numbers[i]>numbers[i+1]:
return numbers[i+1]
return min(numbers[0],numbers[-1])
# 法二:直接返回最小值呗
return min(numbers)
class Solution:
def numWays(self, n: int) -> int:
if n == 0: return 1
if n == 1: return 1
# 1, 1, 2, 3, 5, 8, 13, 21
# f(n) = f(n-1) + f(n-2)
# 考虑是从前一个跳过来的,还是前两个跳过来的
# 从两个之前过来不能一步一步过来,因为那就和从前一个过来重复了
a, b = 1, 1
for i in range(2, n+1):
a, b = b, a+b
return b % 1000000007