241. Different Ways to Add Parentheses

来源:互联网 发布:单片机控制舵机程序 编辑:程序博客网 时间:2024/06/07 17:32

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]


题解:

使用divide and conquer的思想,对input进行遍历,每找到一个operator,就把input分成两份,part1 (operator) part2;对part1和part2分别计算,最后再把两个部分得出的值合起来运算。这个过程会存在一些重复运算,可以使用dp memoization的思想,把计算过的值存储下来,下次可以重复利用。


代码:

public class Solution {    public List<Integer> diffWaysToCompute(String input) {       Map<String, List<Integer>> map = new HashMap<>();       List<Integer> result = computeWithMemo(input, map);       return result;    }        private List<Integer> computeWithMemo(String input, Map<String, List<Integer>> map) {       List<Integer> result = new LinkedList<>();       for(int i = 0; i < input.length(); i++) {           if(input.charAt(i) == '+' || input.charAt(i) == '-' || input.charAt(i) == '*') {               String part1 = input.substring(0, i);               String part2 = input.substring(i+1);               List<Integer> result1;               List<Integer> result2;               if(map.containsKey(part1)) {                  result1 = map.get(part1);                } else {                  result1 = computeWithMemo(part1, map);                }               if(map.containsKey(part2)) {                   result2 = map.get(part2);               } else {                   result2 = computeWithMemo(part2, map);               }               for(Integer o1 : result1) {                   for(Integer o2: result2) {                       result.add(helper(o1,o2,input.charAt(i)));                   }               }           }       }       if(result.size() == 0) {           result.add(Integer.valueOf(input));       }       map.put(input, result);       return result;    }        private int helper(int o1, int o2, char c) {        if(c == '+') {            return o1 + o2;        } else if(c == '*') {            return o1 * o2;        } else {            return o1 - o2;        }    }}


时间复杂度:

假如不使用map记录计算过的值:

f(n) = f(1)+f(2)+..+f(n-1)+f(n-1)+f(n-2)..+f(1) = 2*(f(1)+f(2)+...+f(n-1))=> f(n+1) = 2*(f(1)+f(2)+..+f(n)) = 2*(f(1)+f(2)+...+f(n-1)) + 2f(n) = f(n)+2f(n) = 3f(n) => f(n+1) = 3f(n) = 3*3*f(n-1) = ... = 3^(n+1)Therefore, O(3^n)
题解使用map避免了重复计算,所以应该为


f(n) = f(1)+f(2)+..+f(n-1) => f(n+1) = f(1)+f(2)+..+f(n) = 2*(f(1)+f(2)+...+f(n-1)) = 2f(n)=> f(n+1) = 2f(n) = 2*2*f(n-1) = ... = 2^(n+1)Therefore, O(2^n)


0 0
原创粉丝点击