zoukankan      html  css  js  c++  java
  • 241. Different Ways to Add Parentheses


    July-10-2019

    这个题思路一上来就错了,一开始把重心放在括号上,每个位置可加可不加来做DFS然后就傻逼了。
    比如A+B+C+D是按运算符来做DFS:

    • A + (B+C+D)
    • (A+B) + (C+D)
    • (A+B+C) + D
      他与一般的分治不同的地方在于,左边和右边都是返还List,拿A + (B+C+D)来说,是A+B, A+C, A+D
      然后重复运算很多,记忆搜索可以加速。
    class Solution {
        Map<String, List<Integer>> mem = new HashMap<>();
        public List<Integer> diffWaysToCompute(String input) {
            if (mem.containsKey(input)) return mem.get(input);
            List<Integer> res = new ArrayList<>();
    
            for (int i = 0; i < input.length(); i ++) {
                char tempChar = input.charAt(i);
                if (isOperator(tempChar)) {
                    List<Integer> lResult = diffWaysToCompute(input.substring(0, i));
                    List<Integer> rResult = diffWaysToCompute(input.substring(i + 1));
                    for (int j = 0; j < lResult.size(); j ++) {
                        int left = lResult.get(j);
                        for (int k = 0; k < rResult.size(); k ++) {
                            int right = rResult.get(k);
                            if (tempChar == '-') {
                                res.add(left - right);
                            } else if (tempChar == '+') {
                                res.add(left + right);
                            } else {
                                res.add(left * right);
                            }
                        }
                    }
                }
            }
            
            if (res.isEmpty()) {
                res.add(Integer.valueOf(input));
            }
            mem.put(input, res);
            return res;
        }
        
        public boolean isOperator(char c) {
            return c == '-' || c == '+' || c == '*';
        }
    }
    
  • 相关阅读:
    CodeForces 460B
    CodeForces 456A
    CodeForces462B
    HDU1394(线段树||树状数组)
    HDU1541(树状数组)
    HDU1556(树状数组)
    HDU5726(RMQ&&二分)
    POJ1182(并查集)
    HDU4496(并查集)
    HDU3038(并查集)
  • 原文地址:https://www.cnblogs.com/reboot329/p/11164071.html
Copyright © 2011-2022 走看看