day 27:backtracking

文章介绍了使用回溯法解决LeetCode上的几个问题,包括39题组合Sum、40题组合SumII以及131题回文分割。在39题中,通过深度优先搜索(DFS)寻找数组元素组合成目标值的方法;40题增加了去重的处理,通过排序避免重复;131题则需检查子串是否为回文并在回溯过程中进行判断。
摘要由CSDN通过智能技术生成

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    


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值