2020-08-22
679. 24 点游戏
DFS暴力,每次在数组中找两个数进行组合,一直到剩下一个数为止。
class Solution(object): def judgePoint24(self, nums): """ :type nums: List[int] :rtype: bool """ def dfs(nums): if len(nums)==1: if abs(nums[0]-24) < 1e-6: #print(ans) return True return False for i in range(len(nums)): for j in range(len(nums)): if i==j: continue newnum1 = nums[i]+nums[j] newnum2 = nums[i]-nums[j] newnum3 = nums[i]*nums[j] remain = [nums[k] for k in range(len(nums)) if(k!=i and k!=j)] #ans.append(['(',nums[i],'+',nums[j],')']) if dfs(remain+[newnum1]): return True #ans.pop() #ans.append(['(',nums[i],'-',nums[j],')']) if dfs(remain+[newnum2]): return True #ans.pop() #ans.append(['(',nums[i],'*',nums[j],')']) if dfs(remain+[newnum3]): return True #ans.pop() if nums[j]==0: continue #ans.append(['(',nums[i],'/',nums[j],')']) newnum4 = nums[i]*1.0/nums[j] if dfs(remain+[newnum4]): return True #ans.pop() return False return dfs(nums)
5498. 石子游戏 V
题解: 动态规划, dp[i][j]代表 划分区间(i,j) 能够获得的最大价值,分情况讨论即可。
class Solution(object): def stoneGameV(self, stoneValue): """ :type stoneValue: List[int] :rtype: int """ n = len(stoneValue) d = {} def dfs(start, end): if start>=end: return 0 if (start,end) in d: return d[(start,end)] S,now = 0,0 for i in range(start, end+1): S+=stoneValue[i] ans = 0 first = 0 for i in range(start, end): first += stoneValue[i] second = S - first if first<second: ans = max(ans, dfs(start,i)+first) # 前一段比后一段小 elif first>second: ans = max(ans, dfs(i+1,end)+second) # 后一段比前一段小 else: ans = max(ans, max(dfs(start,i),dfs(i+1,end))+first) # 两端一样大 d[(start,end)] = ans return ans return dfs(0, n-1)