前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 【39、40、77】

Leetcode 【39、40、77】

作者头像
echobingo
发布2019-06-21 16:52:18
4950
发布2019-06-21 16:52:18
举报
问题描述:【DFS、DP】39. Combination Sum
解题思路:

方法1(DFS): Python3 实现:

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        def search(tar):
            for c in candidates:
                if a[-1] <= c:  # 组合数
                    a.append(c)
                    tar -= c
                    if tar == 0:
                        ans.append([])
                        for n in a:
                            ans[-1].append(n)
                        ans[-1].pop(0)  # 把前面的一个0去掉
                    elif tar > 0:
                        search(tar)
                    a.pop()  # 恢复,回溯一步
                    tar += c  # 恢复,回溯一步
                        
        ans = []
        a = [0] # 防止下标越界
        search(target)
        return ans

方法2(DP): Python3 实现:

问题描述:【DFS】40. Combination Sum II
解题思路:

方法1(DFS): Python3 实现:

class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        def search(tar):
            for k, v in enumerate(candidates):
                if not b[k] and a[-1] <= v:
                    a.append(v)
                    b[k] = True
                    tar -= v
                    if tar == 0:
                        tem = []
                        for n in a:
                            tem.append(n)
                        tem.pop(0)
                        if tem not in ans:  # 去重
                            ans.append(tem)
                    elif tar > 0:
                        search(tar)
                    a.pop()
                    b[k] = False
                    tar += v     
        
        a = [0]
        b = [False] * len(candidates)
        ans = []
        search(target)
        return ans
题目描述:【DFS】77. Combinations
解题思路:
Python3 实现:
class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        def search(ind, r, path):
            for i in range(ind, n+1):
                path += [i]
                if r == k:
                    ans.append(path[:])  # 注意这里传引用调用,不然path变化ans也会改变
                else:
                    search(i+1, r+1, path)
                path.pop()
                
        ans = []
        search(1, 1, [])
        return ans
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.06.21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 问题描述:【DFS、DP】39. Combination Sum
  • 解题思路:
  • 问题描述:【DFS】40. Combination Sum II
  • 解题思路:
  • 题目描述:【DFS】77. Combinations
  • 解题思路:
  • Python3 实现:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档