Leetcode 22-24
No. 22 Generate Parentheses (重点)
Solution: DFS
直接代码:
1 class Solution: 2 def generateParenthesis(self, n: int) -> List[str]: 3 if not n: 4 return [] 5 6 left, right, out = n, n, [] 7 self.dfs(left, right, out, "") 8 return out 9 10 def dfs(self, left, right, out, string): 11 if right < left: 12 return 13 if not left and not right: 14 out.append(string) 15 return 16 if left: 17 self.dfs(left-1, right, out, string + "(") 18 if right: 19 self.dfs(left, right-1, out, string + ")")
No. 23 Merge k Sorted Lists (HARD)
No. 24 Swap Nodes in Pairs
Solution:
方法一:Iteratively
1 class Solution: 2 def swapPairs(self, head: ListNode) -> ListNode: 3 if not head: 4 return None 5 6 out = pre = ListNode(None) 7 pre.next = head 8 9 while head and head.next: 10 temp = head.next.next 11 pre.next = head.next 12 pre.next.next = head 13 head.next = temp 14 15 pre = pre.next.next 16 head = pre.next 17 18 return out.next
方法二: Recursively
1 class Solution: 2 def swapPairs(self, head: ListNode) -> ListNode: 3 if head and head.next: 4 temp = head.next 5 head.next = self.swapPairs(temp.next) 6 temp.next = head 7 return temp 8 return head