当前位置:网站首页>leetcode:241. Design priority for operation expression [DFS + Eval]

leetcode:241. Design priority for operation expression [DFS + Eval]

2022-07-01 12:36:00 White speed Dragon King's review

 Insert picture description here

analysis

Choose one of them every time a ? b Add a pair of parentheses
Know to run out of all operators
Then put in a set It is enough to prevent the expressions from being equal

ac code

class Solution:
    def diffWaysToCompute(self, expression: str) -> List[int]:
        ans = []
        operators = ('+', '-', '*')
        def countOperator(s):
            cnt = 0
            for c in s:
                if c in operators:
                    cnt += 1
            
            return cnt
        
        s = set()
        def dfs(nums, ops):
            if len(nums) == 1:
                s.add(nums[0])
                return
            #  Choose one to calculate 
            for i in range(len(nums) - 1):
                new_num = '(' + nums[i] + ops[i] + nums[i + 1] + ')'

                new_nums = nums[:i] + [new_num] + nums[i + 2:]
                new_ops = ops[:i] + ops[i + 1:]
                dfs(new_nums, new_ops)

        # pattern To press ascii code 
        nums = re.split('[*+-]', expression)
        ops = []
        for c in expression:
            if c in operators:
                ops.append(c)
        dfs(nums, ops)
        
        return [eval(exp) for exp in s]

summary

dfs Choose the place you can choose
re.split To distinguish between symbols and numbers , Mainly based on ascii The order of the codes
And then finally through eval Calculate the results of all the different formulas

原网站

版权声明
本文为[White speed Dragon King's review]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/182/202207011234551086.html