美文网首页
2020-04-22

2020-04-22

作者: 木马音响积木 | 来源:发表于2020-04-22 23:42 被阅读0次

针对39题,想起来,爬楼梯问题,分硬币问题。
想到了用 dfs 递归来解决。
1、针对不允许重复,想到了单调栈,这里也就是list
2、针对candidates ,进行排序,可以在循环时,break,加速
3、注意,剪枝。通过单调栈,进行剪枝。
4、注意,列表的引用传递。
5、硬币本身可以重复多次,但要的是组合,不是排序。

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        ans=[]
        c=candidates
        c.sort()
        def dfs(n,st):
            if n<0:return
            if n==0:
                ans.append(st)
                return

            #this level
            for i in c:
                if i>n:break
                if n >= i and (not st or i >= st[-1]): #用单调栈,sort 非必要。
                    dfs(n-i,st+[i])

        dfs(target,[])
        return ans
class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        ans=[]
        c=candidates
        def dfs(n,st):
            if n<0:return
            if n==0:
                ans.append(st);return

            #this level
            for i in c:
                if n >= i and (not st or i >= st[-1]):
                    st.append(i)
                    dfs(n-i,st[:])  #这种写法能看出 回溯的影子。
                    st.pop()   #the most useful point
        dfs(target,[])
        return ans

相关文章

  • 2020-04-23

    2020-04-22 2020-04-22 成长日志第307天 家名:温暖有爱之家 家规:真诚待人不自欺,学会看见...

  • 【日更9】《如何阅读一本书》谈阅读的方法

    2020-04-22 昨天我们谈的阅读的层次...

  • History对象

    本文更新于 2020-04-22。 Html5 使用 history 对象 history.pushState()...

  • 隐私--政策

    隐私政策 版本生效日期:2020-04-22 威火电竞APP(以及下文提到的“我们”、“我们的”或“本app”)是...

  • 隐私--政策

    版本生效日期:2020-04-22 咖咖电竞预约APP(以及下文提到的“我们”、“我们的”或“本app”)是由主体...

  • 儿时恋饮,喝一杯情爱美酒

    儿时恋饮,喝一杯情爱美酒 原创 叶子 恋饮 2020-04-22 18:09 笔墨爱纸,心思爱人。儿时的爱情...

  • 2020-04-22写给淇宝七级之际

    2020-04-22写给淇朵七级之际 淇朵: 淇朵妈昨天收到你的钢琴考级证书了。不光通过,还有更好的消息——成绩不...

  • 同居日记——平凡朴素的生活,才是我想要的

    2020-04-22 ​今天天气不错,是个晴天。连日来的阴雨天气,温度忽冷忽热的变化,真是让人始料未及。 其他地区...

  • 编程语言圣经

    (原创)单薄找土豆2020-04-22 第0x00天 上古时期,人类主要使用二进制编程,人类需要记住数据在内存的地...

  • 花事

    2020-04-22 庚辰月乙未日 为了扒窗入室,或为了报复我们把他关在阳台上,窗台上的几盆绿萝,经常被灰喵打翻一...

网友评论

      本文标题:2020-04-22

      本文链接:https://www.haomeiwen.com/subject/wllbihtx.html