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()