39. Combination Sum

题目来源

LeetCode 39. Combination Sum

自我感觉难度/真实难度: 难

写题时间时长: 2hours

题意:

从一个list中间找到可以相加等于target的数字,可以重复。返回所有可能的情况。
 

分析:

自己一开始是没有什么思路,┏┛┗┓...(((m-__-)m,感觉直接暴力循环肯定是不优雅的
 

自己的代码:


代码效率/结果:

优秀代码:


class Solution:
    def combinationSum(self, can: List[int], tar: int) -> List[List[int]]:
        res=[]
        l=len(can)
        
        def dfs(targ,index,path):
            if targ<0:
                return
            if targ==0:
                res.append(path)
                return
            for i in range(index,l):
                if targ<can[i]:
                    continue
                dfs(targ-can[i],i,path+[can[i]])
        dfs(tar,0,[])
        return res
       

代码效率/结果:
Runtime: 56 ms, faster than 99.16% of Python3 online submissions for Combination Sum.
Memory Usage: 13.2 MB, less than 43.13% of Python3 online submissions for Combination Sum.

自己优化后的代码:


 


反思改进策略:

  1. 对各类算法及常见的题型没有总结。总结起来
  2. 好的算法还可以进一步优化,提升时间效率。思考哪些情况是无效的,去除一些没有必要的操作
posted @ 2019-05-30 18:07  dgi  阅读(144)  评论(0编辑  收藏  举报