[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);
            }
        }
    }

 

posted @ 2015-11-07 12:19  lasclocker  阅读(606)  评论(0编辑  收藏  举报