• Leetcode练习之分治


    1. 给表达式加括号

    241. Different Ways to Add Parentheses (Medium)

    class Solution {
        public List<Integer> diffWaysToCompute(String input) {
            List<Integer> ways = new ArrayList<>();
            for(int i = 0; i < input.length();i++){
                char c = input.charAt(i);
                if(c == '+' || c == '-' || c == '*'){
                    List<Integer> left = diffWaysToCompute(input.substring(0,i));
                    List<Integer> right = diffWaysToCompute(input.substring(i + 1));
                    for(int l : left) {
                        for(int r : right) {
                            switch(c) {
                                case '+':
                                ways.add(l + r);
                                break;
                                case '-':
                                ways.add(l - r);
                                break;
                                case '*':
                                ways.add(l * r);
                                break;
                            }
                        }
                    }
                }
            }
            if(ways.size() == 0){
                ways.add(Integer.valueOf(input));
            }
            return ways;
        }
    }

    2. 不同的二叉搜索树

    95. Unique Binary Search Trees II (Medium)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public List<TreeNode> generateTrees(int n) {
            if(n < 1) {
                return new LinkedList<TreeNode>();
            }
            return generateSubtrees(1, n);
        }
    
        private List<TreeNode> generateSubtrees(int s, int e) {
            List<TreeNode> res = new LinkedList<TreeNode>();
            if (s > e) {
                res.add(null);
                return res;
            }
            for(int i = s; i <= e; ++i) {
                List<TreeNode> leftSubtrees = generateSubtrees(s, i - 1);
                List<TreeNode> rightSubtrees = generateSubtrees(i + 1, e);
                for (TreeNode left : leftSubtrees) {
                    for (TreeNode right : rightSubtrees){
                        TreeNode root = new TreeNode(i);
                        root.left = left;
                        root.right = right;
                        res.add(root);
                    }
                }
            }
            return res;
        }
    }
  • 相关阅读:
    Java 8 新特性-菜鸟教程 (8) -Java 8 日期时间 API
    Java 8 新特性-菜鸟教程 (7) -Java 8 Nashorn JavaScript
    Java 8 新特性-菜鸟教程 (6) -Java 8 Optional 类
    心理相关
    matlab和Visio安装
    论文资料搜集整理(研究现状)
    调式相关
    梅花落与折杨柳
    混合高斯模型——学习笔记
    NSCT,非下采样Contourlet变换——学习笔记
  • 原文地址:https://www.cnblogs.com/coding-fairyland/p/12693758.html
Copyright © 2020-2023  润新知