2000/7500
此次比赛成绩十分惨烈,卡在第三题过不去。用的0-1背包+回溯,一直超时,后来看题解就是一个简单的枚举,我服了。第四题看都没看。
T1
class Solution:
def countHillValley(self, nums: List[int]) -> int:
lth=len(nums)
index=1
def get_left(t,val):
while t>=1 and nums[t]==val:
t-=1
return nums[t]
ans=0
while index<=lth-2:
if nums[index]==nums[index+1]:
index+=1
continue
else:
left=get_left(index,nums[index])
right=nums[index+1]
if (nums[index]>left and nums[index]>right) or (nums[index]<left and nums[index]<right):
ans+=1
index+=1
return ans
T2
class Solution:
def countCollisions(self, directions: str) -> int:
stack=[]
ans=0
for c in directions:
if len(stack)==0:
stack.append(c)
else:
if c=="S":
while len(stack)!=0 and stack[-1]=="R":
ans+=1
stack.pop()
stack.append("S")
elif c=="L":
ok=False
if stack[-1]=="R" or stack[-1]=="S":
if stack[-1]=="R":
ans+=2
else:
ans+=1
ok=True
stack.pop()
while len(stack)!=0 and stack[-1]=="R":
ans+=1
stack.pop()
if ok:
stack.append("S")
else:
stack.append("L")
else:
stack.append(c)
return ans
T3
一共大概170个样例,过了120个,我为何会想到01背包?
class Solution:
def maximumBobPoints(self, numArrows: int, aliceArrows: List[int]) -> List[int]:
#12件物品
w,val=[0]*13,[0]*13
for i in range(1,13):
w[i]=aliceArrows[i-1]+1
val[i]=i-1
n=12
dp=[[0 for j in range(numArrows+1)]for i in range(n+1)]
for i in range(1,n+1):
for j in range(1,numArrows+1):
if j<w[i]:
dp[i][j]=dp[i-1][j]
else:
dp[i][j]=max(dp[i-1][j],dp[i-1][j-w[i]]+val[i])
ans=[0]*12
x,y=12,numArrows
while x>0:
if dp[x][y]==dp[x-1][y]:
ans[x-1]=0
x-=1
elif dp[x][y]==dp[x-1][y-w[x]]+val[x]:
ans[x-1]=w[x]
y-=w[x]
x-=1
ans[0]=y
return ans
下午新增T3,AC代码
class Solution:
def maximumBobPoints(self, numArrows: int, aliceArrows: List[int]) -> List[int]:
#枚举每一种状态
ans,maxscore=[0]*12,0
for i in range(1,1<<12):
need,score=0,0
for j in range(12):
#判断当前位置是否需要射箭 即判断当前i的j位置是否为1
if 1 & (i>>j):
need+=(aliceArrows[11-j]+1)
score+=(11-j)
if need<=numArrows:
if maxscore<score:
maxscore=score
for j in range(12):
if 1 & (i>>j):
ans[11-j]=aliceArrows[11-j]+1
else:
ans[11-j]=0
leave=numArrows-sum(ans)
if leave>0:
ans[0]+=leave
return ans