zoukankan      html  css  js  c++  java
  • 【hard】282. Expression Add Operators

    Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +-, or * between the digits so they evaluate to the target value.

    Example 1:

    Input: num = "123", target = 6
    Output: ["1+2+3", "1*2*3"] 
    

    Example 2:

    Input: num = "232", target = 8
    Output: ["2*3+2", "2+3*2"]

    Example 3:

    Input: num = "105", target = 5
    Output: ["1*0+5","10-5"]

    Example 4:

    Input: num = "00", target = 0
    Output: ["0+0", "0-0", "0*0"]
    

    Example 5:

    Input: num = "3456237490", target = 9191
    Output: []

    方法: dfs, 递归
    class Solution(object):
        def addOperators(self, num, target):
            
            def dfs(idx, cal, tot, last, res):
                if idx == len(num):
                    if tot == target:
                        res.append(cal)
                    return
                for i in range(idx, len(num)):
                    x = int(num[idx: i+1])
                    if idx == 0:
                        dfs(i+1, str(x), x, x, res)
                    else:
                        dfs(i + 1, cal + "+" + str(x), tot + x, x, res)
                        dfs(i + 1, cal + "-" + str(x), tot - x, -x, res)
                        dfs(i + 1, cal + "*" + str(x), tot - last + last * x, last * x, res)
                    # if x == 0: # not necessary
                    #     break
                    
                
            res = []
            dfs(0, "", 0, 0, res)
            return res
    

      

  • 相关阅读:
    DHCP Option 60 的理解
    程序中的魔鬼数字
    开源GUI-Microwindows之程序入口分析
    http报错之return error code:401 unauthorized
    内存泄漏以及常见的解决方法
    怎样对ListView的项进行排序
    getline函数
    JavaFx初探
    ListBox控件的操作与实现
    SQLite的SQL语法
  • 原文地址:https://www.cnblogs.com/sherry-yang/p/12364990.html
Copyright © 2011-2022 走看看