leetcode「组合」题目汇总 回溯法

2020-04-30  本文已影响0人  winter_sweetie

2020/4/30

39. 组合总和

题意
栗子
输入: candidates = [2,3,6,7], target = 7,
所求解集为:
[
  [7],
  [2,2,3]
]
关键点

回溯要素

代码
class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        res = []
        subset = []
        self.backtrack(candidates, 0, subset, res, target)
        return res

    def backtrack(self, candidates, k, subset, res, target):
        if target == 0:
            res.append(subset[:])
            return
        if target < 0:
            return

        for i in range(k, len(candidates)):
            # 如果candidates有重复元素,需要加一句:
            # if i != k and candidates[i] == candidates[i - 1]:
            # continue
            # 当然,前提是candidates有序
            subset.append(candidates[i])
            self.backtrack(candidates, i, subset, res, target - candidates[i])
            # 如果元素不可以重复选取,需要改成
            # self.backtrack(candidates, i + 1, subset, res, target - candidates[i])
            del subset[-1]

40. 组合总和 II

题意
栗子
输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]
关键点:刚好和上道题相反

回溯要素

代码
class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        res = []
        subset = []
        # 先排序
        candidates.sort()
        self.backtrack(candidates, 0, subset, res, target)
        return res

    def backtrack(self, candidates, k, subset, res, target):
        if target == 0:
            res.append(subset[:])
            return
        
        if target < 0:
            return
        for i in range(k, len(candidates)):
            # 去重/剪枝
            if i != k and candidates[i] == candidates[i - 1]:
                continue
            subset.append(candidates[i])
            # 因为candidates的每个数字只能使用一次,所以i + 1
            self.backtrack(candidates, i + 1, subset, res, target - candidates[i])
            del subset[-1]

216. 组合总和 III

题意
栗子
输入: k = 3, n = 9
输出: [[1,2,6], [1,3,5], [2,3,4]]
关键点

回溯要素

代码
class Solution:
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        combination = []
        res = []
        self.backtrack(k, n, 1, combination, res)
        return res

    def backtrack(self, k, n, m, combination, res):
        if k == len(combination):
            if n == 0:
                res.append(combination[:])
            return
        
        for i in range(m, 10):
            combination.append(i)
            self.backtrack(k, n - i, i + 1, combination, res)
            del combination[-1]

377. 组合总和 Ⅳ

题意
栗子
nums = [1, 2, 3]
target = 4

所有可能的组合为:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)

请注意,顺序不同的序列被视作不同的组合。

因此输出为 7。
关键点
回溯要素
算法优化

使用哈希映射表mp来存储{target: times},避免重复计算。

代码
from collections import defaultdict
class Solution:
    def combinationSum4(self, nums: List[int], target: int) -> int:
        self.res = 0
        mp = defaultdict(int)
        return self.backtrack(nums, target, mp)

    def backtrack(self, nums, target, mp):
        if target in mp:
            return mp[target]
        if target == 0:
            self.res += 1 
            return 1
        if target < 0:
            return 0
        
        res = 0
        for i in range(len(nums)):
            res += self.backtrack(nums, target - nums[i], mp)
        mp[target] = res
        return res
dp方法
class Solution:
    def combinationSum4(self, nums: List[int], target: int) -> int:
        dp = [0] * (target + 1)
        # dp[0]初始化为1
        dp[0] = 1
        # 循环顺序一定不能乱
        for i in range(1, target + 1):
            for j in range(len(nums)):
                if nums[j] > i:
                    continue
                dp[i] += dp[i - nums[j]]
        return dp[target]

518. 零钱兑换 II

栗子
输入: amount = 5, coins = [1, 2, 5]
输出: 4
解释: 有四种方式可以凑成总金额:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
tricky之处
错误代码
from collections import defaultdict

class Solution:
    def change(self, amount: int, coins: List[int]) -> int:
        mp = defaultdict(int)
        return self.dfs(amount, coins, 0, mp)

    def dfs(self, amount, coins, k, mp):
        if amount in mp:
            return mp[amount]
        if amount == 0:
            return 1
        if amount < 0:
            return 0
        
        res = 0
        # 写成range(len(coins))是一样的
        for i in range(k, len(coins)):
            res += self.dfs(amount - coins[i], coins, i, mp)
        
        mp[amount] = res
        return res
解释
正确做法
正确代码
from collections import defaultdict

class Solution:
    def change(self, amount: int, coins: List[int]) -> int:
        mp = defaultdict(int)
        return self.dfs(amount, coins, 0, mp)

    def dfs(self, amount, coins, k, mp):
        if k == len(coins):
            if amount == 0:
                return 1
            return 0
        if amount < 0:
            return 0
        if (k, amount) in mp:
            return mp[(k, amount)]
        
        res = 0
        for i in range(amount // coins[k] + 1): # 注意加1
            res += self.dfs(amount - i * coins[k], coins, k + 1, mp)
        
        mp[(k, amount)] = res
        return res
dp方法
class Solution:
    def coinChange(self, coins: List[int], amount: int) -> int:
        dp = [float('inf')] * (amount + 1)
        dp[0] = 0
        for i in range(amount + 1):
            for c in coins:
                if i - c < 0:
                    continue # 不能break,因为硬币不一定升序
                dp[i] = min(dp[i], dp[i-c] + 1)
        return dp[-1] if dp[-1] != float('inf') else -1

77. 组合

题意
栗子
输入: n = 4, k = 2
输出:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]
关键点
回溯要素
代码
class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        combination = []
        res = []
        self.backtrack(n, k, combination, res)
        return res
        
    def backtrack(self, n, k, combination, res):
        if k == 0:
            res.append(combination[:])
            return
        
        if n < k:
            return 

        for i in range(n, 0, -1):
            combination.append(i)
            self.backtrack(i - 1, k - 1, combination, res)
            del combination[-1]

17. 电话号码的字母组合

题意
栗子
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
回溯要素
代码
class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        if len(digits) == 0:
            return []
        mp = {'2': ['a', 'b', 'c'], '3': ['d', 'e', 'f'], '4': ['g', 'h', 'i'], '5': ['j', 'k', 'l'], '6': ['m', 'n', 'o'], '7': ['p', 'q', 'r', 's'], '8': ['t', 'u', 'v'], '9': ['w', 'x', 'y', 'z']}
        res = []
        self.backtrack(digits, 0, mp, '', res)
        return res

    
    def backtrack(self, digits, k, mp, combination, res):
        if k == len(digits):
            res.append(combination) #string是值传递,不是引用传递
            return
        for ch in mp[digits[k]]:
            self.backtrack(digits, k + 1, mp, combination + ch, res)
上一篇下一篇

猜你喜欢

热点阅读