Different Ways to Add Parentheses

來源:互聯網
上載者:User

標籤:

問題描述

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 recursivelyList<Integer> left = diffWaysToCompute(input.substring(0, i));List<Integer> right = diffWaysToCompute(input.substring(i+1));// calculate each partfor (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 numberlist.add(Integer.valueOf(input));}return list;}}

  

Different Ways to Add Parentheses

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.