Share my 22-line commented java code


  • 3
    M
    public class Solution {
        public List<Integer> diffWaysToCompute(String input) {
            List<Integer> curResults = new ArrayList<>();  // current level results
            for (int i=0; i<input.length(); ++i) {
                char c = input.charAt(i);
                if (c=='+' || c=='-' || c=='*') {  // 以每一个算符为分割, 分割为[左边所有可能结果] + 这个算符 + [右边所有可能结果]
                    List<Integer> leftResults = diffWaysToCompute(input.substring(0, i));
                    List<Integer> rightResults = diffWaysToCompute(input.substring(i+1));
                    for (Integer left: leftResults) {
                        for (Integer right: rightResults) {
                            int result = 0;
                            if (c == '+') { result = left + right; }
                            else if (c == '-') { result = left - right; }
                            else { result = left * right; }
                            curResults.add(result);
                        }
                    }
                }
            }
            if (curResults.size() == 0) { 
                curResults.add(Integer.parseInt(input));  // base case, a single number
                return curResults;
            }
            return curResults;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.