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

    Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +- and *.

    Example 1:

    Input: "2-1-1"
    Output: [0, 2]
    Explanation: 
    ((2-1)-1) = 0 
    (2-(1-1)) = 2

    Example 2:

    Input: "2*3-4*5"
    Output: [-34, -14, -10, -10, 10]
    Explanation: 
    (2*(3-(4*5))) = -34 
    ((2*3)-(4*5)) = -14 
    ((2*(3-4))*5) = -10 
    (2*((3-4)*5)) = -10 
    (((2*3)-4)*5) = 10

    Approach #1: 

    namespace studycat {
        int add(int x, int y) { return x + y; }
        int sub(int x, int y) { return x - y; }
        int mul(int x, int y) { return x * y; }
    }
    
    class Solution {
    public:
        vector<int> diffWaysToCompute(string input) {
            return helper(input);
        }
        
    private:
        unordered_map<string, vector<int>> memo;
        
        const vector<int>& helper(const string& input) {
            if (memo.count(input)) return memo[input];
            
            vector<int> ans;
            
            for (int i = 0; i < input.length(); ++i) {
                char op = input[i];
                
                if (op == '+' || op == '-' || op == '*') {
                    const string left = input.substr(0, i);
                    const string right = input.substr(i+1);
    
                    const vector<int>& l = helper(left);
                    const vector<int>& r = helper(right);
                    
                    std::function<int(int, int)> f;
    
                    switch(op) {
                        case '+': f = studycat::add; break;
                        case '-': f = studycat::sub; break;
                        case '*': f = studycat::mul; break;
                    }
                    
                    for (int i : l) 
                        for (int j : r) 
                            ans.push_back(f(i, j));
         
                }
            }
            if (ans.empty())
                ans.push_back(std::stoi(input));
            
            memo[input].swap(ans);
            return memo[input];
        }
    };
    

      

    Analysis:

    http://zxi.mytechroad.com/blog/leetcode/leetcode-241-different-ways-to-add-parentheses/

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    第三次作业成绩
    现代程序设计 作业6
    动态期末成绩
    课堂作业成绩公布(游戏服务器以及客户端设计)
    第二次作业(homework-02)成绩公布
    指定长度,页面显示换行
    java学习流程
    对象比对
    开发语言转型
    Asp.Net 自定义储存Session方式
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10331475.html
Copyright © 2011-2022 走看看