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);
                }
            }
        }
  • 相关阅读:
    数据库迁移后,孤立账号解决办法
    一个很BT的汇总算法
    Working with tempdb in SQL Server 2005
    PHP 获取淘宝商品价格 函数
    Python 基础(一)环境搭建
    Python > 3.0导入库整理
    [转]ios输入框被键盘挡住的解决办法
    App更新说明的写作
    [转]Python 常用代码片段
    python BeautifulSoup 安装
  • 原文地址:https://www.cnblogs.com/lasclocker/p/4944816.html
Copyright © 2011-2022 走看看