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

    ((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]

    解决思路

    其实挺巧妙的,主要参考https://leetcode.com/discuss/48488/c-4ms-recursive-method

    理解这句话很重要:The key idea for this solution is: each operator in this string could be the last operator to be operated.

    核心思想是递归,然后边界条件是输入的字符串仅为数字。

    程序

    public class DifferentWaysToCompute {
    	public List<Integer> diffWaysToCompute(String input) {
    		List<Integer> list = new ArrayList<Integer>();
    		for (int i = 0; i < input.length(); i++) {
    			char c = input.charAt(i);
    			if (c == '+' || c == '-' || c == '*') {
    				// Split input string into two parts and solve them recursively
    				List<Integer> left = diffWaysToCompute(input.substring(0, i));
    				List<Integer> right = diffWaysToCompute(input.substring(i+1));
    				
    				// calculate each part
    				for (int j = 0; j < left.size(); j++) {
    					for (int k = 0; k < right.size(); k++) {
    						if (c == '+') {
    							list.add(left.get(j) + right.get(k));
    						} else if (c == '-') {
    							list.add(left.get(j) - right.get(k));
    						}else {
    							list.add(left.get(j) * right.get(k));
    						}
    					}
    				}
    			}
    		}
    		
    		if (list.isEmpty()) {
    			// input string contains only number
    			list.add(Integer.valueOf(input));
    		}
    		
    		return list;
    	}
    }
    

      

  • 相关阅读:
    无声的吐槽csdn
    成长
    最近忙的头发都油油的
    pycharm5工具免费分享及安装教程
    分布式版本控制git常见问题之gitignore冲突
    感觉自己还是太年轻,还有很多东西不会
    关于laravel5.2仓库的建立,以及简单调用
    乎,前所未有的挑战!
    嘿嘿,无聊的时候,来点好玩的,翻滚吧,杀马特!!!
    随便说说
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4682081.html
Copyright © 2011-2022 走看看