`

Different Ways to Add Parentheses

阅读更多
Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +, - and *.


Example 1
Input: "2-1-1".

((2-1)-1) = 0
(2-(1-1)) = 2
Output: [0, 2]


Example 2
Input: "2*3-4*5"

(2*(3-(4*5))) = -34
((2*3)-(4*5)) = -14
((2*(3-4))*5) = -10
(2*((3-4)*5)) = -10
(((2*3)-4)*5) = 10
Output: [-34, -14, -10, -10, 10]

输出所有可能的结果。我们采用分治法,当遇到字符‘+’ ,’-‘ ,’*‘ 时就把字符串分为两段,然后递归求出左半部分可右半部分能有的结果,然后在将左半部分和有半部分根据当前的字符求出当前可能的结果。当for循环结束就返回结果。代码如下:
public class Solution {
    public List<Integer> diffWaysToCompute(String input) {
        List<Integer> list = new ArrayList<Integer>();
        if(input == null || input.length() == 0) return list;
        if(input.indexOf("+") < 0 && input.indexOf("-") < 0 && input.indexOf("*") < 0) {
            list.add(Integer.parseInt(input));
            return list;
        }
        for(int i = 0; i < input.length(); i++) {
            char tem = input.charAt(i);
            if(tem == '+' || tem == '-' || tem == '*') {
                List<Integer> left = diffWaysToCompute(input.substring(0, i));
                List<Integer> right = diffWaysToCompute(input.substring(i + 1, input.length()));
                for(int m : left) 
                    for(int n : right) {
                        switch(input.charAt(i)) {
                            case('+') :
                                list.add(m + n);
                                break;
                            case('-') :
                                list.add(m - n);
                                break;
                            case('*') :
                                list.add(m * n);
                                break;
                        }
                    }
            }
        }
        return list;
    }
}
分享到:
评论

相关推荐

    SQLPrompt_7.4.1.603

    Improvements to nested parentheses Case statements with comments now align correctly Now adds a space before aliases following function calls Added "Place BEGIN keyword on new line" option. You can ...

    SQLPrompt_7.4.0.471

    Improvements to nested parentheses Case statements with comments now align correctly Now adds a space before aliases following function calls (forum) Added "Place BEGIN keyword on new line" option ...

    « ACM模板收集Let the Balloon Rise » Catalan数

    2.the number of ways in which parentheses can be placed in a sequence of numbers to be multiplied, two at a time; 3.the number of rooted, trivalent trees with n+1 nodes; (hdu 1131) 4.the number of ...

    The-parentheses-matching-the-test.rar_Parentheses Matching_The T

    用C语言编写的,括号匹配的检验能够让人轻易的学会C语言和数据结构的使用。

    HOW TO IMPROVE YOUR BUSINESS LETTERS

    the author and year of publication in parentheses within the body of your text (Lawrence 1999). Then include the full citation in a reference section at the end of your paper: The Ten Secrets of ...

    parentheses:如何通过放置括号来给出最大数量

    parentheses:如何通过放置括号来给出最大数量

    程序员面试宝典LeetCode刷题手册

    2. Add Two Numbers 3. Longest Substring Without Repeating Characters 4. Median of Two Sorted Arrays 7. Reverse Integer 9. Palindrome Number 11. Container With Most Water 13. Roman to Integer 15. 3Sum ...

    TCP IP Illustrated, Vol 1 The Protocols 2nd.pdf

    This notation, the name of the command followed by a number in parentheses, is the normal way of referring to Unix commands. The number in parentheses is the section number in the Unix manual of the ...

    mariadb5-win32

    MariaDB is a drop-in replacement for MySQL. MariaDB strives to be the logical choice for database professionals looking for a ... All links will redirect you to external sites, noted in parentheses.

    leetcode2-valid_parentheses:代码挑战:有效括号

    leetcode 2 有效括号 给定一个只包含字符'(' , ')' , '{' , '}' , '['和']'的字符串,确定输入字符串是否有效。 输入字符串在以下情况下有效: * 左括号必须由相同类型的括号封闭。...类别:堆栈、序列处理

    Visual Assist X 2107官方原版 带破解补丁

    Fixed case in which parentheses were not automatically matched when complete with any character was enabled and '(' was used to commit the listbox selection. (case=97044) Improved results of Goto and ...

    cpp-算法精粹

    Decode Ways Distinct Subsequences Word Break Word Break II Dungeon Game House Robber House Robber II House Robber III Range Sum Query - Immutable Range Sum Query 2D - Immutable 图 Clone Graph 位操作 ...

    SQL Prompt_9.1.13.5130破解版

    SP-6937 : Parentheses style settings no longer apply to table hints, so they always remain on the same line as the preceding WITH. SP-6958 : Preserve whitespace between alias and table name in ...

    ebook-Practical C Programming, 3rd Edition(ebook).pdf

    1. Multiply and divide come before add and subtract. 2. Put parentheses around everything else. Consider two programs. One was written by a clever programmer using all the tricks. The program ...

    Clojure for the Brave and True

    For weeks, months?—nay!—from the very moment ... Grab your best pair of parentheses—you're about to embark on an epic journey into the world of Clojure!, Covers Clojure 1.7Requires Java 1.6 or later

    ImageMagick图片批量处理

    -loop iterations add Netscape loop extension to your GIF animation -mask filename associate a mask with the image -mattecolor color frame color -monitor monitor progress -orient type image ...

    Parentheses:编码练习

    括弧 编码练习 给定一串左括号和右括号,检查它是否平衡。 我们有 3 种类型的括号:圆括号:()、方括号:[] 和大括号:{}。 假设字符串不包含除这些之外的任何其他字符,没有空格单词或数字。 提醒一下,平衡括号...

    Parentheses Classifier-开源

    括号分类器采用一组括号的内容,并将其分类为几个类别之一。 它包括一个带括号的数据提取器和分类器。

    highlight-parentheses.el:移至SourceHut

    此项目已移至来源: ://sr.ht/~tsdh/highlight-parentheses.el/

    SQL Prompt_9.1.8.4871破解版

    Code analysis is now less likely to produce out of memory exceptions when loading many tabs at once. Removed formatting override "Place parenthesised FROM sources on new line". SP-6667 : Parentheses ...

Global site tag (gtag.js) - Google Analytics