zoukankan      html  css  js  c++  java
  • leetcode 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
    

    长见识了,大概知道分治的用法了, 额,求二叉树的高度的思维和 分治很像啊, 快排应该就是分治算法的典型应用

    遍历输入字符串,遇到一个运算符就分别遍历运算符的左边和右边,通过这样的递归就能求到该运算符左边和右边的所有可能的值, 递归的终止情况是,字符串中只有数字;

     1 class Solution {
     2 public:
     3     vector<int> diffWaysToCompute(string input) {
     4         vector<int> ans;
     5         for(int i=0; i<input.size(); i++){
     6             if(input[i]=='-' || input[i]=='+' || input[i]=='*'){
     7                 vector<int> l=diffWaysToCompute(input.substr(0, i));
     8                 vector<int> r=diffWaysToCompute(input.substr(i+1));
     9                 for(int j=0; j<l.size(); j++){
    10                     for(int k=0; k<r.size(); k++){
    11                         if(input[i]=='-') ans.push_back(l[j]-r[k]);
    12                         else if(input[i]=='+') ans.push_back(l[j]+r[k]);
    13                         else if(input[i]=='*') ans.push_back(l[j]*r[k]);
    14                     }
    15                 }
    16             }
    17         }
    18         if(ans.empty()) ans.push_back(stoi(input));
    19         return ans;
    20     }
    21 };
    有疑惑或者更好的解决方法的朋友,可以联系我,大家一起探讨。qq:1546431565
  • 相关阅读:
    CLR via C#深解笔记三
    CLR via C#深解笔记二
    CLR via C#深解笔记一
    C#参考:Linq 概述
    JavaScript
    jQuery
    JavaScript
    云原生
    python模块----optparse模块、argparse模块 (命令行解析模块)
    python模块----pymysql模块 (连接MySQL数据库)
  • 原文地址:https://www.cnblogs.com/mr-stn/p/9218921.html
Copyright © 2011-2022 走看看