T1 LC202 快乐数

  1. class Solution:
  2. def isHappy(self, n: int) -> bool:
  3. left=sum([int(i)*int(i) for i in str(n)])
  4. right=sum([int(i)*int(i) for i in str(left)])
  5. if left==1 or right==1:return True
  6. while left!=right:
  7. left=sum([int(i)*int(i) for i in str(left)])
  8. right=sum([int(i)*int(i) for i in str(right)])
  9. right=sum([int(i)*int(i) for i in str(right)])
  10. if right==1 or left==1:
  11. return True
  12. return False

T2 LC92 反转列表

  1. class Solution:
  2. def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
  3. # m对应节点是头结点,直接翻转
  4. if m == 1: return self.reverse(head, m, n)
  5. count = 1
  6. h = head
  7. while h: #找到m前一个节点preRev
  8. if count == m - 1:
  9. preRev = h
  10. h = h.next
  11. count += 1
  12. headRev = self.reverse(preRev.next, m, n)
  13. preRev.next = headRev
  14. return head
  15. def reverse(self, head, m, n):
  16. '''
  17. 该函数完成m-n的翻转以及翻转后与剩余链表相连两个任务
  18. '''
  19. pre, cur = None, head
  20. #翻转m-n链表
  21. for _ in range(n - m + 1):
  22. pre, pre.next, cur = cur, pre, cur.next
  23. head.next = cur #与剩余链表相连
  24. return pre

T3 LC51 N皇后

  1. class Solution:
  2. def solveNQueens(self, n: int) -> List[List[str]]:
  3. def could_place(row, col):
  4. return not (cols[col] + hill_diagonals[row - col] + dale_diagonals[row + col])
  5. def place_queen(row, col):
  6. queens.add((row, col))
  7. cols[col] = 1
  8. hill_diagonals[row - col] = 1
  9. dale_diagonals[row + col] = 1
  10. def remove_queen(row, col):
  11. queens.remove((row, col))
  12. cols[col] = 0
  13. hill_diagonals[row - col] = 0
  14. dale_diagonals[row + col] = 0
  15. def add_solution():
  16. solution = []
  17. for _, col in sorted(queens):
  18. solution.append('.' * col + 'Q' + '.' * (n - col - 1))
  19. output.append(solution)
  20. def backtrack(row = 0):
  21. for col in range(n):
  22. if could_place(row, col):
  23. place_queen(row, col)
  24. if row + 1 == n:
  25. add_solution()
  26. else:
  27. backtrack(row + 1)
  28. remove_queen(row, col)
  29. cols = [0] * n
  30. hill_diagonals = [0] * (2 * n - 1)
  31. dale_diagonals = [0] * (2 * n - 1)
  32. queens = set()
  33. output = []
  34. backtrack()
  35. return output

今日学习总结

提交了学校CPP OJ的作业