Python基於xlrd模組處理合並單元格
阿新 • • 發佈:2020-07-28
回溯法的本質是一個基於深度優先搜尋(DFS)的窮舉的過程
- 新增值
- 判定現有結果是否滿足條件
- DFS
- 回退
簡單回溯法的使用
-
問題:輸入一顆二叉樹的根節點和一個整數,打印出二叉樹中結點值的和為輸入整數的所有路徑。路徑定義為從樹的根結點 開始往下一直到葉結點所經過的結點形成一條路徑。
-
解決:
class Solution: # 返回二維列表,內部每個列表表示找到的路徑 def FindPath(self, root, expectNumber): path, spare = [],[] def recur(root,tar): if not root: return spare.append(root.val) tar -= root.val if not root.left and not root.right and tar == 0: path.append(list(spare)) recur(root.left, tar)#深度遍歷 recur(root.right, tar) spare.pop() #回溯 recur(root,expectNumber) return path
字串的排列
-
問題:輸入一個字串,按字典序打印出該字串中字元的所有排列。例如輸入字串abc,則按字典序打印出由字元a,b,c所能排列出來的所有字串abc,acb,bac,bca,cab和cba。
-
解決:
class Solution: def Permutation(self, ss): # write code here res = [] cache = list(ss) def recur(x): if x == len(cache)-1: res.append("".join(cache)) return dic = [] for i in range(x,len(cache)): if cache[i] in dic: continue dic.append(cache[i]) cache[i], cache[x] = cache[x], cache[i] recur(x+1) cache[i], cache[x] = cache[x], cache[i] recur(0) return sorted(res)