代码随想录算法训练营第二十七天|39. 组合总和、40.组合总和II、131.分割回文串

发布时间:2024年01月10日

39. 组合总和

题目:

给你一个?无重复元素?的整数数组?candidates?和一个目标整数?target?,找出?candidates?中可以使数字和为目标数?target?的 所有?不同组合?,并以列表形式返回。你可以按?任意顺序?返回这些组合。

candidates?中的?同一个?数字可以?无限制重复被选取?。如果至少一个数字的被选数量不同,则两种组合是不同的。?

对于给定的输入,保证和为?target?的不同组合数少于?150?个。

输入: candidates = [2,3,5]      target = 8
输出: [[2,2,2,2],[2,3,3],[3,5]]

思路:

????????所给的数组里的数字是不重复发。

? ? ? ?

代码:

class Solution:
    # 递归函数
    def backtracking(self, total, result, startIndex, path, target, candidates):
        # 终止条件
        if total > target:
            return
        if total == target:
            result.append(path[:])
            return

        # 遍历
        for i in range(startIndex, len(candidates)):
            total += candidates[i]
            path.append(candidates[i])
            # 调用递归
            self.backtracking(total, result, i, path, target, candidates)
            # 上面  是从i不是i+1的原因:每个数字可以重复使用
            total -= candidates[i]   # 弹出
            path.pop()  # 回溯

    # 主函数
    def combinationSum(self, candidates, target):
        result = []
        self.backtracking(0, result, 0, [], target, candidates)
        return result

40.组合总和II

题目:

给定一个候选人编号的集合?candidates?和一个目标数?target?,找出?candidates?中所有可以使数字和为?target?的组合。

candidates?中的每个数字在每个组合中只能使用?一次?。

注意:解集不能包含重复的组合。?

思路:

和上一题的区别:每个数字不能重复使用,但是列表里有重复的数字。

所以要去重,利用used数组判断,这是本题解答的核心。

代码:

class Solution:
    def backtracking(self, candidates, target, total, startIndex, used, path, result):
        if total == target:
            result.append(path[:])
            return
        for i in range(startIndex, len(candidates)):
            if i > startIndex and candidates[i] == candidates[i - 1] and not used[i - 1]:  # 去重
                continue

            if total + candidates[i] > target:
                break

            total += candidates[i]
            path.append(candidates[i])
            used[i] = True  # candidates[i]被使用过
            self.backtracking(candidates, target, total, i + 1, used, path, result)  # 继续搜索
            used[i] = False  # 没有被用过
            total -= candidates[i]
            path.pop()

    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        used = [False] * len(candidates)  # 将used数组全部初始化为False,表示所有的元素都还没有被使用过
        result = []
        candidates.sort()  # 给数组排序
        self.backtracking(candidates, target, 0, 0, used, [], result)
        return result

131.分割回文串

题目:

给你一个字符串?s,请你将?s?分割成一些子串,使每个子串都是?回文串?。返回?s?所有可能的分割方案。

回文串?是正着读和反着读都一样的字符串。

示例 1:

输入:s = "aab"
输出:[["a","a","b"],["aa","b"]]

思路:

看过视频的思路

重要的是多了一步判断回文的函数,以及把startIndex作为切割线,以及每次收集结果的时候利用切片。

代码:

class Solution:
    # 判断是不是回文串
    def is_palindrome(self, s: str, start: int, end: int) -> bool:
        i:int = start
        j:int = end
        while i < j:
            if s[i] != s[j]:
                return False
            i += 1
            j -= 1
        return True

    # 递归
    def backtracking(self, s, path, result, startIndex):
        # 终止条件
        if startIndex == len(s):
            result.append(path[:])
            return
        # 遍历  单层递归逻辑
        for i in range(startIndex, len(s)):
            if self.is_palindrome(s, startIndex, i):  # 调用判断回文串的函数
                path.append(s[startIndex:i + 1])  # 切片
                self.backtracking(s,  path, result,i + 1)
                path.pop()

    # 主函数
    def partition(self, s: str):
        result = []
        self.backtracking(s,  [], result,0)
        return result

文章来源:https://blog.csdn.net/2302_80810661/article/details/135469205
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。