首页 > 其他 > 详细

241. Different Ways to Add Parentheses

时间:2019-07-10 15:19:08      阅读:88      评论:0      收藏:0      [点我收藏+]


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 == '*';
    }
}

241. Different Ways to Add Parentheses

原文:https://www.cnblogs.com/reboot329/p/11164071.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!