2020-08-19
110. 平衡二叉树
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def isBalanced(self, root): """ :type root: TreeNode :rtype: bool """ def dfs(root): if root is None: return 0,True lh , lok = dfs(root.left) rh , rok = dfs(root.right) ok = True if not lok or not rok : ok = False if abs(rh-lh)>1: ok = False h = max(lh, rh)+1 return h, ok _, ret = dfs(root) return ret
109. 有序链表转换二叉搜索树
快慢指针+二分
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def sortedListToBST(self, head): """ :type head: ListNode :rtype: TreeNode """ def build(head): if head is None: return None pre = None slow = head fast = head while fast and fast.next: pre = slow slow = slow.next fast = fast.next.next root = TreeNode(slow.val) if pre: pre.next = None root.left = build(head) root.right = build(slow.next) return root return build(head)
647. 回文子串
dp: dp[i][j]代表 i~j是否为回文串。
class Solution(object): def countSubstrings(self, s): """ :type s: str :rtype: int """ dp = []*len(s) for i in range(len(s)): dp.append([0]*len(s)) ans = 0 for l in range(1,len(s)+1): for i in range(len(s)): if i+l-1 >= len(s): continue if l==1: dp[i][i] = 1 elif l==2: dp[i][i+1] = (s[i]==s[i+1]) else : dp[i][i+l-1] = dp[i+1][i+l-2] and s[i]==s[i+l-1] #print(i, i+l-1) if dp[i][i+l-1]: ans+=1 return ans
51. N皇后
标记主副对角线 和列 进行爆搜。
class Solution(object): def solveNQueens(self, n): """ :type n: int :rtype: List[List[str]] """ vis_col = [0]*n vis_l = [0]*2*n vis_r = [0]*2*n col = [] res = [] def dfs(row): if row == n: mould = [] for i in range(n): mould.append("") for j in range(n): if col[i]==j: mould[i] += 'Q' else: mould[i] += '.' res.append(mould) return for i in range(n): if vis_col[i]==0 and vis_l[i-row+n]==0 and vis_r[i+row]==0: vis_col[i] = 1 vis_l[i-row+n] = 1 vis_r[i+row] = 1 col.append(i) dfs(row+1) col.pop() vis_col[i] = 0 vis_l[i-row+n] = 0 vis_r[i+row] = 0 dfs(0) return res
61. 旋转链表
构造环形链表
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def rotateRight(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ if head is None: return head tail = head p = head l = 0 while p: tail = p p = p.next l+=1 tail.next = head k = k%l k = l-k-1 # 找到前一个点 while k: head = head.next k-=1 newhead = head.next head.next = None return newhead