• 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 == '*';
        }
    }
    
  • 相关阅读:
    将node.js代码放到阿里云上,并启动提供外部接口供其访问
    Linux内核深度解析之内核互斥技术——读写信号量
    man 1 2 3 4...
    Android Sepolicy 相关工具
    selinux misc
    ext4 mount options
    tune2fs cmd(ext fs)
    /dev/tty node
    kernel misc
    fork & vfork
  • 原文地址:https://www.cnblogs.com/reboot329/p/11164071.html
Copyright © 2020-2023  润新知