Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity。
分析:加入直接合并的话,每次需要找到k个数中的最小,一共需要查找k*max(n)次,复杂度为O(k^2 *n)
这里采用分治的思想,每次合并的数目大于等于3,就分发下去,知道合并两个。合并两个的复杂度为O(n) .O(T) = 2*O(T/2) + n,所以复杂度为nlog(k)
1 def mergeKLists(self, lists): 2 if not lists: 3 return None 4 return self.mergeKListsHelp(lists, 0, len(lists) - 1) 5 def mergeKListsHelp(self, lists, start, end): 6 if start == end: 7 return lists[start] 8 if start + 1 == end: 9 return self.mergeTwoList(lists[start], lists[end]) 10 divider = start + (end - start)/2 11 return self.mergeTwoList(self.mergeKListsHelp(lists, start, divider),self.mergeKListsHelp(lists, divider + 1, end)) 12 def mergeTwoList(self, node1, node2): 13 14 if not node1: 15 return node2 16 if not node2: 17 return node1 18 head = ListNode(0) 19 tmp = head 20 while node1 and node2: 21 if node1.val < node2.val: 22 tmp.next = node1 23 tmp = tmp.next 24 node1 = node1.next 25 else: 26 tmp.next = node2 27 tmp = tmp.next 28 node2 = node2.next 29 while node1: 30 tmp.next = node1 31 tmp = tmp.next 32 node1 = node1.next 33 while node2: 34 tmp.next = node2 35 tmp = tmp.next 36 node2 = node2.next 37 return head.next
Expression Add Operators
Given a string that contains only digits 0-9
and a target value, return all possibilities to add binary operators (not unary) +
, -
, or *
between the digits so they evaluate to the target value.
递归。对于每个数间位置,把原来字符串分为前后两半,前半和后半分别递归求解,然后前半加减乘后半。最后如果到达末尾,看结果是不是target。
需要注意的几个点:
如果选择乘,那么之前的结果就要减去前一个数,因为此时应该首先与后边的数结合。
减的时候,前一个数应该存为-cur
不存在012这样的数,所以遇到012这样的情况应该提早结束递归。
1 def addOperators(self, num, target): 2 """ 3 :type num: str 4 :type target: int 5 :rtype: List[str] 6 """ 7 res = [] 8 self.dfs(res, num, target, '', 0, 0, 0) 9 return res 10 def dfs(self,res, num, target, path, pos, val, mulVal): 11 if pos == len(num): 12 if val == target: 13 res.append(path) 14 return 15 length = len(num) 16 for i in range(pos,length): 17 if i!=pos and num[pos] == '0': 18 break 19 cur = int(num[pos:i + 1]) 20 if pos == 0: 21 self.dfs(res, num, target, path + str(cur), i + 1, cur, cur) 22 else: 23 self.dfs(res, num, target, path + '+' + str(cur), i + 1, val + cur, cur) 24 self.dfs(res, num, target, path + '-' + str(cur), i + 1, val - cur, -cur) 25 self.dfs(res, num, target, path + '*' + str(cur), i + 1, val - mulVal + mulVal * cur, mulVal * cur)