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

    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".

    ((2-1)-1) = 0
    (2-(1-1)) = 2

    Output: [0, 2]


    Example 2

    Input: "2*3-4*5"

    (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

    Output: [-34, -14, -10, -10, 10]

    Credits:
    Special thanks to @mithmatt for adding this problem and creating all test cases.

     1 public class Solution {
     2     public List<Integer> diffWaysToCompute(String input) {
     3         List<Integer> ans = new ArrayList<Integer>();
     4         for(int i = 0; i < input.length(); i++){
     5             char c = input.charAt(i);
     6             if(c != '+' && c != '-' && c != '*') continue;
     7             List<Integer> left = diffWaysToCompute(input.substring(0,i));
     8             List<Integer> right = diffWaysToCompute(input.substring(i+1,input.length()));
     9             for(int le : left){
    10                 for(int ri : right){
    11                     if(c == '+') ans.add(le+ri);
    12                     else if(c == '-') ans.add(le-ri);
    13                     else if(c == '*') ans.add(le*ri);
    14                 }
    15             }
    16         }
    17         if(ans.size() == 0) ans.add(Integer.parseInt(input));
    18         return ans;
    19     }
    20 }

    使用分治的思想。

     
  • 相关阅读:
    快速设置Scrapy随机的IP代理
    快速设置随机的UserAgent
    windows安装flask并创建虚拟环境
    数电和模电比较
    程序员如何写出一份好的文档?
    Qt简介
    基于 Qt的聊天工具
    如何将word组合图形保存成png
    2015电赛点滴
    函数定义
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5619922.html
Copyright © 2011-2022 走看看