8.3

1.第一题:
在这里插入图片描述
用二分法,一直缩小范围。

class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
        n=len(nums)
        head=0
        tail=n-1
        while head<=tail:
            mid=head+(tail-head)//2
            if nums[mid]<target:
                head=mid+1
            elif nums[mid]>target:
                tail=mid-1
            else:
                if nums[head]<target:
                    head+=1
                if nums[tail]>target:
                    tail-=1
                if nums[head]==nums[tail]:
                    return [head,tail]
        
        return [-1,-1]

2.第二题:
在这里插入图片描述
回溯法:

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        if len(candidates)==0:
            return []
        candidates.sort()
        path=[]
        res=[]
        self.HS(candidates,target,0,path,res)
        return res
    
    def HS(self,candidates,target,begin,path,res):
        path=path.copy()
        #递归出口,余数为0
        if target==0:
            res.append(path)#记录符合条件的结果
            return 
        #若当前路径有可能可行。
        for i in range(begin,len(candidates)):#我们现在到begin的节点上了
            if target-candidates[i]<0:#剪枝条件
                return 
            path.append(candidates[i])#记录当前位置
            self.HS(candidates,target-candidates[i],i,path,res)
            path.pop()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值