defbacktracking(self, nums, temp, ans, used): if len(temp) == len(nums): ans.append(list(temp)) for i in range(len(nums)): if used[i] or i>0and nums[i]==nums[i-1] andnot used[i-1]: # 判断条件 continue temp.append(nums[i]) used[i] = True# 记录访问 self.backtracking(nums, temp, ans, used) used[i] = False temp.pop()
defbacktracking(self, nums, temp, res, start): res.append(list(temp)) for i in range(start,len(nums)): temp.append(nums[i]) self.backtracking(nums, temp, res, i+1) temp.pop()
90. Subsets II
因为input含有duplicate,所以在进入backtracking之前需要检查
1 2 3 4 5 6 7 8
defbacktracking(self, nums, temp, res, start): res.append(list(temp)) for i in range(start,len(nums)): if i > start and nums[i] == nums[i-1]: continue temp.append(nums[i]) self.backtracking(nums, temp, res, i+1) temp.pop()
classSolution(object): defcombinationSum3(self, k, n): """ :type k: int :type n: int :rtype: List[List[int]] """ res = [] self.backtracking(k,n,[],res,1) return res
defbacktracking(self, k, target, temp, res, start): if len(temp) > k: return elif len(temp) == k and target == 0: res.append(list(temp)) else: for i in range(start, 10): temp.append(i) self.backtracking(k, target - i, temp, res, i+1) temp.pop()
Medium
22 Generate Parentheses
recursion rule 就是判断left,right的count啦,直到满足right == n
1 2 3 4 5 6 7
defdfs(self,temp, left, right, res,n): if left < n: self.dfs(temp+'(',left+1,right,res,n) if right < left: self.dfs(temp+')',left, right+1, res,n) if right==n: res.append(temp)
320. Generalized Abbreviation
这道题debug了好久,困惑于如何使得数字和字母不会在base case的时候重复导出
1 2 3 4
4 3d 2r1 2rd ...
1 2 3 4 5 6 7 8 9 10
defbacktrack(res, word, pos, string, count): if pos == len(word): if count>0: string += str(count) res.append(string) else: backtrack(res,word,pos+1,string,count+1) ## 这个track保证了index每次不断加1 从而在base的时候输出,然后每一次count同时加1,为了记录count backtrack(res, word, pos+1, string + (str(count) if count>0else"")+ word[pos], 0) ## 这个是为了退一步,先保存当前的count数字,然后因为数字不能连续,所以+word【index】,同时把count清0