leetcode刷题——算法(5):分治

分治(2.15)

 

 

1. 给表达式加括号

一开始未做出

2. 不同的二叉搜索树

一开始未做出

 1. 给表达式加括号

241. Different Ways to Add Parentheses (Medium)

https://leetcode-cn.com/problems/different-ways-to-add-parentheses/

加上备忘录的分治法:单纯分治存在超时现象

class Solution {
public:
    map> mp;  //备忘录
    vector diffWaysToCompute(string input) {
        if(mp.find(input)!=mp.end()) return mp[input];  
        int n=input.size();
        vector res;
        if(n==0) return res;
        for(int i=0;i left=diffWaysToCompute(input.substr(0,i));
            vector right=diffWaysToCompute(input.substr(i+1));
            for(auto l:left)
                for(auto r:right)
                    switch(c){
                        case '+':res.push_back(l+r);break;
                        case '-':res.push_back(l-r);break;
                        case '*':res.push_back(l*r);break;
                    }
        }
        if(res.empty()){
            int num=0;
            for(int i=0;i

2. 不同的二叉搜索树

95. Unique Binary Search Trees II (Medium)

https://leetcode-cn.com/problems/unique-binary-search-trees-ii/

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector generateTrees(int n) {
        if(n<1) return vector{};
        else return generate(1,n);
    }
    vector generate(int left,int right){
        vector res;
        if(left>right) res.push_back(NULL); 
        for(int i=left;i<=right;i++){
            vector lt=generate(left,i-1);
            vector rt=generate(i+1,right);
            for(auto l:lt)
               for(auto r:rt){
                   TreeNode* t=new TreeNode(i);
                   t->left=l;
                   t->right=r;
                   res.push_back(t);
               }
        }
        return res;
    }
};

 

你可能感兴趣的:(LeetCode)