day 27:backtracking!
Leetcode 39. Combination Sum
class Solution:
def __init__(self):
self.path = []
self.res = []
def combinationSum(self, c: List[int], t: int):
self.dfs(c,t)
return self.res
def dfs(self, arr, t):
if arr==None: return
if sum(self.path)>t: return
if sum(self.path)==t:
self.res.append(self.path[:])
for i in range(len(arr)):
self.path.append(arr[i])
self.dfs(arr[i:], t)
self.path.pop()
Leetcode 40. Combination Sum II
去重 去了一小时 服了 没做出来 直接复制粘贴
class Solution(object):
def combinationSum2(self, candidates, target):
# Sorting is really helpful, se we can avoid over counting easily
candidates.sort()
result = []
self.combine_sum_2(candidates, 0, [], result, target)
return result
def combine_sum_2(self, nums, start, path, result, target):
# Base case: if the sum of the path satisfies the target, we will consider
# it as a solution, and stop there
if not target:
result.append(path)
return
for i in range(start, len(nums)):
# Very important here! We don't use `i > 0` because we always want
# to count the first element in this recursive step even if it is the same
# as one before. To avoid overcounting, we just ignore the duplicates
# after the first element.
if i > start and nums[i] == nums[i - 1]:
continue
# If the current element is bigger than the assigned target, there is
# no need to keep searching, since all the numbers are positive
if nums[i] > target:
break
# We change the start to `i + 1` because one element only could
# be used once
self.combine_sum_2(nums, i + 1, path + [nums[i]],
result, target - nums[i])
Leetcode 131. Palindrome Partitioning:
class Solution:
def __init__(self):
self.path = []
self.res = []
self.flag = True
def partition(self, s: str) -> List[List[str]]:
self.backtrack(s, 0)
return self.res
def backtrack(self, s, start):
# Base Case
if start>= len(s):
self.res.append(self.path[:])
return
# 单层递归逻辑
for i in range(start, len(s)):
# 此次比其他组合题目多了一步判断:
# 判断被截取的这一段子串([start_index, i])是否为回文串
temp = s[start:i+1]
if temp == temp[::-1]: # 若反序和正序相同,意味着这是回文串
self.path.append(temp)
self.backtrack(s, i+1) # 递归纵向遍历:从下一处进行切割,判断其余是否仍为回文串
self.path.pop()
else:
continue