zoukankan      html  css  js  c++  java
  • [leetcode] 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.
    
    Examples: 
    "123", 6 -> ["1+2+3", "1*2*3"] 
    "232", 8 -> ["2*3+2", "2+3*2"]
    "105", 5 -> ["1*0+5","10-5"]
    "00", 0 -> ["0+0", "0-0", "0*0"]
    "3456237490", 9191 -> []

    分析:构造成如下结构,利用DFS解答:

                                               123
    
                                           /    |    
                  第一个数                 1    12   123
                                        /       
                  第二个数              2   23     3
                                     /
                  第三个数           3

    另外注意:在遇到乘法(*)时,新的当前值(curSum)为:(curSum - preSum) * value + preSum,新的上一次值(preSum)仍为preSum.

    Java代码如下:

        public List<String> addOperators(String num, int target) {
            List<String> result = new ArrayList<String>();
            operator(num, target, result, 0, 0, "");
            return result;
        }
    
        private void operator(String num, int target, List<String> result, long curSum, long preSum, String tmp) {
            if (num.length() == 0 && curSum == target) {
                result.add(tmp);
                return;
            }
            for (int i = 1; i <= num.length(); i++) { //此处是<=,而不是<
                String first = num.substring(0, i);
                if (first.length() > 1 && first.charAt(0) == '0') {
                    return;
                }
                long value = Long.parseLong(first);
                String second = num.substring(i);
                if (! "".equals(tmp)) {
                    operator(second, target, result, curSum + value, curSum, tmp + "+" + first);
                    operator(second, target, result, curSum - value, curSum, tmp + "-" + first);
                    operator(second, target, result, (curSum - preSum) * value + preSum, preSum, tmp + "*" + first);
                } else {
                    operator(second, target, result, curSum + value, curSum, first);
                }
            }
        }
  • 相关阅读:
    html的URL参数传值问题
    html背景图片拉伸至全屏
    Laravel 用户验证Auth::attempt fail的问题
    HTML中meta的应用
    ubuntu升级php版本
    Laravel 目录结构分析
    css颜色渐变在不同浏览器的设置
    谷歌浏览器(Chrome)离线包的下载方法!
    RAD Studio 10 up1欢迎页证书不可用
    MySQL
  • 原文地址:https://www.cnblogs.com/lasclocker/p/4944816.html
Copyright © 2011-2022 走看看