leetcode每日一题202110

282 给表达式添加运算符

难点在于:

我们考虑如果只有 + 和 - 的话,可以很容易将运算和回溯搜索所有表达进行结合。但当存在 * 时,由于存在运算优先级的问题,我们需要记录形如 a + b * c 中的乘法部分。

 我的思路:

典型的回溯。

回溯终止条件是:

if len(path)==len(num)+len(num)-1 and cal_value(path)==target:
    res.append(path)

我这个终止条件只考虑到了比如

123,6。   1+2+3这种情况.

 比如 105,5。10-5 这种情况没有考虑到。

这个终止条件有问题,考虑不全。

class Solution(object):
    def addOperators(self, num, target):
        """
        :type num: str
        :type target: int
        :rtype: List[str]
        """
        def cal_value(s):
            #计算字符串的值
            fuhao = 1
            left = 0
            right = 2
            if s[fuhao] == '+':
                cur = int(s[left]) + int(s[right])
            elif s[fuhao] == '-':
                cur = int(s[left]) - int(s[right])
            elif s[fuhao] == '*':
                cur = int(s[left]) * int(s[right])
            while right < 2 * len(num) - 2:
                fuhao = fuhao + 2
                right = right + 2
                if s[fuhao] == '+':
                    cur = cur + int(s[right])
                elif s[fuhao] == '-':
                    cur = cur - int(s[right])
                elif s[fuhao] == '*':
                    cur = cur * int(s[right])
            return cur
        def backtracing(num,target,path,start):
            if len(path)==len(num)+len(num)-1 and cal_value(path)==target:
                res.append(path)
            for i in range(start,len(num)):
                if i!=len(num)-1:
                    for f in ['+','-','*']:
                        cur=num[i]+f
                        path=path+cur
                        backtracing(num,target,path,i+1)
                        path=path[:len(path)-2]
                else:
                    cur=num[i]
                    path = path + cur
                    backtracing(num,target,path,i+1)
                    path=path[:len(path)-2]
        res=[]
        path=""
        start=0
        backtracing(num,target,path,start)
        return res

这个代码能通过一部分,不能全通过。

力扣

class Solution(object):
    def addOperators(self, num, target):
        """
        :type num: str
        :type target: int
        :rtype: List[str]
        """
        def backtracing(num,target,path,pre,sum,start,res):
            #递归终止条件
            if start==len(num) and sum==target:
                res.append(''.join(path[:]))
            for i in range(start,len(num)):
                #处理case,如果开始是0,不继续
                if num[start]=='0' and i!=start:
                    break
                s=num[start:i+1]
                val=int(s)
                if start==0:
                    path.append(s)
                    backtracing(num,target,path,val,sum+val,i+1,res)
                    path.pop()
                else:
                    path.append('+')
                    path.append(s)
                    backtracing(num,target,path,val,sum+val,i+1,res)
                    path.pop()
                    path.pop()

                    path.append('-')
                    path.append(s)
                    backtracing(num,target,path,-val,sum-val,i+1,res)
                    path.pop()
                    path.pop()

                    path.append('*')
                    path.append(s)
                    backtracing(num,target,path,val*pre,sum-pre+val*pre,i+1,res)
                    path.pop()
                    path.pop()
        path=[]
        pre=0
        sum=0
        start=0
        res=[]
        backtracing(num,target,path,pre,sum,start,res)
        return res

227 基本计算器

166 分数到小数

class Solution(object):
    def fractionToDecimal(self, numerator, denominator):
        """
        :type numerator: int
        :type denominator: int
        :rtype: str
        """
        #模拟竖式乘法
        a = numerator
        b = denominator
        #如果本身能够整除,直接返回计算结果
        if a%b ==0:
            return str(a/b)
        res=[]
        #如果其一为负数,先追加负号
        if a * b < 0:
            res.append('-')
        a=abs(a)
        b=abs(b)
        #计算小数点前的部分,并将余数赋值给 a
        a1=a/b
        res.append(str(a1))
        res.append(".")
        a=a%b
        maps={}
        #判断是不是循环小数
        circle=0
        while a>0:
            #从第几个小数位开始循环,从res的第几位开始循环
            maps[a]=len(res)
            a=a*10
            res.append(a/b)
            a=a%b
            #如果当前余数之前出现过,则将 [出现位置 到 当前位置] 的部分抠出来(循环小数部分)
            if a in maps:
                circle=maps[a]
                break
        print(res)
        print(res[0:2])
        ans=""
        for i in res[0:2]:
            ans=ans+i
        for i in range(2,len(res)):
            if i==circle:
                ans=ans+"("
            ans=ans+str(res[i])
        if circle>0:
            ans=ans+")"
        return ans

230 二叉搜索树中第 k 小元素

 leetcode—hot100-树1_MaYingColdPlay的博客-CSDN博客

638 大礼包

python可变对象与不可变对象 - 知乎

python可变对象与不可变对象。

问题:一个元素是可变对象还是不可变对象呢,例如单词拆分,递归的时候,是用一个self.res来在每层递归中进行判断的。猜测是可变对象,查一下

class Solution(object):
    def dfs(self,needs, price, special, maps):
        ans = 0
        needs_str = ''
        for c in needs:
            needs_str = needs_str+str(c) + '_'
        if needs_str in maps.keys():
            return maps[needs_str]
        else:
            # 最弱的方式;不购买大礼包
            for h in range(len(price)):
                ans = ans + needs[h] * price[h]
            # 遍历每个大礼包,购买它,看是不是能获得更便宜的价格
            for i in range(len(special)):
                valid = True
                anext = []
                # 购买的数量不能超过needs
                for j in range(len(price)):
                    if special[i][j] > needs[j]:
                        valid = False
                        break
                if not valid:
                    continue
                if valid:
                    # 用anext数组更新买了当前大礼包之后,还需要购买多少商品
                    for j in range(len(price)):
                        anext.append(needs[j] - special[i][j])
                # 更新最小值
                ans = min(ans, self.dfs(tuple(anext),price,special, maps) + special[i][-1])
            needs_str=''
            for c in needs:
                needs_str=needs_str+str(c)+'_'
            maps[needs_str] = ans
            return ans
    def shoppingOffers(self, price, special, needs):
        """
        :type price: List[int]
        :type special: List[List[int]]
        :type needs: List[int]
        :rtype: int
        """
        maps={}
        return self.dfs(tuple(needs),price,special,maps)

注意在递归的时候,列表要转化为元祖。因为列表的值会在递归的时候改变,然后变不回去了。可变参数与不可变参数。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值