【LeetCode】39. 组合总和 & 40. 组合总数 II & 216. 组合总和 III & 1~n 这n个数组合成 m

172 篇文章 4 订阅
148 篇文章 3 订阅

一、组合总和(可以重复选择)

1.1 题目描述

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的数字可以无限制重复被选取。

说明:

所有数字(包括 target)都是正整数。
解集不能包含重复的组合。

示例 1:

输入:candidates = [2,3,6,7], target = 7,
所求解集为:
[
  [7],
  [2,2,3]
]

示例 2:

输入:candidates = [2,3,5], target = 8,
所求解集为:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

提示:

1 <= candidates.length <= 30
1 <= candidates[i] <= 200
candidate 中的每个元素都是独一无二的。
1 <= target <= 500

1.2 解题思路 & 代码

参考:LeetCode题解

回溯算法 + 剪枝

from typing import List


class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        size = len(candidates)
        if size == 0:
            return []

        # 剪枝是为了提速,在本题非必需
        candidates.sort()
        # 在遍历的过程中记录路径,它是一个栈
        path = []
        res = []
        # 注意要传入 size ,在 range 中, size 取不到
        self.__dfs(candidates, 0, size, path, res, target)
        return res

    def __dfs(self, candidates, begin, size, path, res, target):
        # 先写递归终止的情况
        if target == 0:
            # Python 中可变对象是引用传递,因此需要将当前 path 里的值拷贝出来
            # 或者使用 path.copy()
            res.append(path[:])
            return

        for index in range(begin, size):
            residue = target - candidates[index]
            # “剪枝”操作,不必递归到下一层,并且后面的分支也不必执行
            if residue < 0:
                break
            path.append(candidates[index])
            # 因为下一层不能比上一层还小,起始索引还从 index 开始
            self.__dfs(candidates, index, size, path, res, residue)
            path.pop()


if __name__ == '__main__':
    candidates = [2, 3, 6, 7]
    target = 7
    solution = Solution()
    result = solution.combinationSum(candidates, target)
    print(result)

========================================================

========================================================

二、组合总和 II(不可以重复选择)

2.1 题目描述

给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

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

说明:
所有数字(包括目标数)都是正整数。
解集不能包含重复的组合。

示例 1:

输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

示例 2:

输入: candidates = [2,5,2,1,2], target = 5,
所求解集为:
[
  [1,2,2],
  [5]
]

2.2 解题思路 & 代码

参考:LeetCode题解

回溯算法 + 剪枝

编码的不同在于下一层递归的起始索引不一样。

第 39 题:还从候选数组的当前索引值开始。
第 40 题:从候选数组的当前索引值的下一位开始。

相同之处:解集不能包含重复的组合。

为了使得解集不包含重复的组合。我们想一想,如何去掉一个数组中重复的元素,除了使用哈希表以外,我们还可以先对数组升序排序,重复的元素一定不是排好序以后的第 1 个元素和相同元素的第 1 个元素。根据这个思想,我们先对数组升序排序是有必要的。候选数组有序,对于在递归树中发现重复分支,进而“剪枝”也是有效的。

from typing import List


class Solution:

    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        def dfs(begin, path, residue):
            if residue == 0:
                res.append(path[:])
                return

            for index in range(begin, size):
                if candidates[index] > residue:
                    break

                if index > begin and candidates[index - 1] == candidates[index]:
                    continue

                path.append(candidates[index])
                dfs(index + 1, path, residue - candidates[index])
                path.pop()

        size = len(candidates)
        if size == 0:
            return []

        candidates.sort()
        res = []
        dfs(0, [], target)
        return res

========================================================

三、组合 III

3.1 题目描述

找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。

说明:

所有数字都是正整数。
解集不能包含重复的组合。

示例 1:

输入: k = 3, n = 7
输出: [[1,2,4]]

示例 2:

输入: k = 3, n = 9
输出: [[1,2,6], [1,3,5], [2,3,4]]

3.2 解题思路 & 代码

回溯 + 剪枝

  1. 初试化结果数组 r e s res res
  2. 定义回溯函数 h e l p ( c o u n t , i , t m p , t a r g e t ) help(count,i,tmp,target) help(count,i,tmp,target),其中 c o u n t count count 表示当前已经使用的数字数, i i i 表示当前访问的数字, t m p tmp tmp 表示当前中间结果, t a r g e t target target 表示下一步的目标和。
    1)若 c o u n t = = k count == k count==k,说明已经使用了 k k k 个数:
    2)若 t a r g e t = = 0 target==0 target==0,表示 t m p tmp tmp 的和等于 n n n,将 t m p tmp tmp 加入 r e s res res
    3) r e t u r n return return
  3. 遍历区间 [ i , 10 ) [i,10) [i,10)
    1)剪枝,若 j > t a r g e t j>target j>target,说明接下来的数字都比目标和大, b r e a k break break
    2)执行回溯 h e l p ( c o u n t + 1 , j + 1 , t m p + [ j ] , t a r g e t − j ) help(count+1,j+1,tmp+[j],target−j) help(count+1,j+1,tmp+[j],targetj)
  4. 执行 h e l p ( 0 , 1 , [ ] , n ) help(0,1,[],n) help(0,1,[],n)
  5. 返回 r e s res res
class Solution:
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        res=[]
        def helper(count,i,tmp,target):
            # print(count,i,tmp,target)
            if(count==k):
                if(target==0):
                    res.append(tmp)
                return
            for j in range(i,10):
                if(j>target):
                    break
                helper(count+1,j+1,tmp+[j],target-j)
        helper(0,1,[],n)
        return res

复杂度分析

  1. 时间复杂度: O ( n ! ) O(n!) O(n!),进行了一次遍历。
  2. 空间复杂度: O ( 1 ) O(1) O(1)

参考:

  1. LeetCode题解

========================================================

四、1~n 这n个数组合成 m

4.1 题目描述

1~n 一共 n 个数,随机取出某些数形成组合,求和为 m,打印所有的组合方式

4.2 解题思路 & 代码

参考:寻找组合数,求出从整数1到n中和为m的所有组合

采用背包问题原理,仅考虑具有最大的数字n是否存在与结果集合中,考虑以下两种情形:

(1)n在集合中,剩下的n-1个数字需要组成一个和为n-m的组合;

(2)n不在集合中,剩下的n-1个数字仍需要组成和为m的组合;

由于需要给出所有的组合可能,因此是一个回溯的过程。

算法设计思路:

由于是个回溯递归的过程,因此需要首先给出递归终止条件:当需要求和的数字小于等于0或所有数字都用完了的时候,就是程序终止的时候。

用一个列表数组item存储当前的候选集合,result列表存放最终的满足条件的结果,当满足条件时,将item加入result中。

因此,回溯的代码如下:

def find_combine(item, n, m, result):
    if n <= 0 or m <= 0:
        return
    if n == m:
        result.append(item + [n])
    item.append(n)
    find_combine(item, n-1, m-n, result)
    item.pop()
    find_combine(item, n-1, m, result)

if __name__ == '__main__':
	n = 9
	m = 10
    item = []
    result = []
    find_combine(item, 9, 10, result)
    for r in result:
        print(r)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值