27天【程式碼隨想錄演算法訓練營34期】第七章 回溯演算法part03(● 39. 組合總和 ● 40.組合總和II ● 131.分割回文串)

MiraMira發表於2024-04-15

39. 組合總和
怎麼才能避免重複?比現在數小的數就別append到path裡面了,之前肯定都試過了

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        result = []
        candidates.sort()
        self.backtracking(candidates, 0, [], target, result)
        return result
    def backtracking(self, candidates, startingIndex, path, sum_, result):
        if sum_ == 0:
            result.append(path[:])
            return
        for i in range(startingIndex, len(candidates)):
            if sum_ - candidates[i] < 0:
                break
            path.append(candidates[i])
            self.backtracking(candidates, i, path, sum_-candidates[i], result)
            path.pop()

40.組合總和II

class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        result = []
        candidates.sort()
        self.backtracking(candidates, result, target, [], 0)
        return result
    def backtracking(self, candidates, result, sum_, path, startingIndex):
        if sum_ == 0:
            result.append(path[:])
            return
        for i in range(startingIndex, len(candidates)):
            if i > startingIndex and candidates[i] == candidates[i-1]:
                continue
            if candidates[i] > sum_:
                break
            path.append(candidates[i])
            self.backtracking(candidates, result, sum_ - candidates[i], path, i+1)
            path.pop()

131.分割回文串

class Solution:
    def partition(self, s: str) -> List[List[str]]:
        result = []
        self.backtracking(s, [], 0, result)
        return result
    def backtracking(self, s, path, index, result):
        if index >= len(s):
            result.append(path[:])
            return
        for i in range(index, len(s)):
            if self.is_palindrome(s, index, i):
                path.append(s[index:i+1])
                self.backtracking(s, path, i+1, result)
                path.pop()
    
    def is_palindrome(self, s, start, end):
        while start <= end:
            if s[start] != s[end]:
                return False
            start += 1
            end -= 1
        return True

相關文章