T1 LC202 快乐数
class Solution:
def isHappy(self, n: int) -> bool:
left=sum([int(i)*int(i) for i in str(n)])
right=sum([int(i)*int(i) for i in str(left)])
if left==1 or right==1:return True
while left!=right:
left=sum([int(i)*int(i) for i in str(left)])
right=sum([int(i)*int(i) for i in str(right)])
right=sum([int(i)*int(i) for i in str(right)])
if right==1 or left==1:
return True
return False
T2 LC92 反转列表
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
# m对应节点是头结点,直接翻转
if m == 1: return self.reverse(head, m, n)
count = 1
h = head
while h: #找到m前一个节点preRev
if count == m - 1:
preRev = h
h = h.next
count += 1
headRev = self.reverse(preRev.next, m, n)
preRev.next = headRev
return head
def reverse(self, head, m, n):
'''
该函数完成m-n的翻转以及翻转后与剩余链表相连两个任务
'''
pre, cur = None, head
#翻转m-n链表
for _ in range(n - m + 1):
pre, pre.next, cur = cur, pre, cur.next
head.next = cur #与剩余链表相连
return pre
T3 LC51 N皇后
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
def could_place(row, col):
return not (cols[col] + hill_diagonals[row - col] + dale_diagonals[row + col])
def place_queen(row, col):
queens.add((row, col))
cols[col] = 1
hill_diagonals[row - col] = 1
dale_diagonals[row + col] = 1
def remove_queen(row, col):
queens.remove((row, col))
cols[col] = 0
hill_diagonals[row - col] = 0
dale_diagonals[row + col] = 0
def add_solution():
solution = []
for _, col in sorted(queens):
solution.append('.' * col + 'Q' + '.' * (n - col - 1))
output.append(solution)
def backtrack(row = 0):
for col in range(n):
if could_place(row, col):
place_queen(row, col)
if row + 1 == n:
add_solution()
else:
backtrack(row + 1)
remove_queen(row, col)
cols = [0] * n
hill_diagonals = [0] * (2 * n - 1)
dale_diagonals = [0] * (2 * n - 1)
queens = set()
output = []
backtrack()
return output
今日学习总结
提交了学校CPP OJ的作业