|
| 1 | +package javacode.solutions; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +// [Problem] https://leetcode.com/problems/different-ways-to-add-parentheses |
| 6 | +class DifferentWaysToAddParentheses { |
| 7 | + // Recursion |
| 8 | + public List<Integer> diffWaysToCompute(String input) { |
| 9 | + List<Integer> permutations = new ArrayList<>(); |
| 10 | + for (int i = 0; i < input.length(); i++) { |
| 11 | + char c = input.charAt(i); |
| 12 | + if (c == '-' || c == '+' || c == '*') { |
| 13 | + String left = input.substring(0, i); |
| 14 | + String right = input.substring(i + 1); |
| 15 | + List<Integer> leftPermutations = diffWaysToCompute(left); |
| 16 | + List<Integer> rightPermutations = diffWaysToCompute(right); |
| 17 | + for (int leftPermutation : leftPermutations) { |
| 18 | + for (int rightPermutation : rightPermutations) { |
| 19 | + int permutation = compute(leftPermutation, rightPermutation, c); |
| 20 | + permutations.add(permutation); |
| 21 | + } |
| 22 | + } |
| 23 | + } |
| 24 | + } |
| 25 | + if (permutations.size() == 0) { |
| 26 | + permutations.add(Integer.valueOf(input)); |
| 27 | + } |
| 28 | + return permutations; |
| 29 | + } |
| 30 | + |
| 31 | + private int compute(int num1, int num2, char operator) { |
| 32 | + if (operator == '*') { |
| 33 | + return num1 * num2; |
| 34 | + } else if (operator == '+') { |
| 35 | + return num1 + num2; |
| 36 | + } else { |
| 37 | + return num1 - num2; |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + // Test |
| 42 | + public static void main(String[] args) { |
| 43 | + DifferentWaysToAddParentheses solution = new DifferentWaysToAddParentheses(); |
| 44 | + |
| 45 | + String input = "2*3-4*5"; |
| 46 | + List<Integer> output = solution.diffWaysToCompute(input); |
| 47 | + |
| 48 | + // expected: [-34, -14, -10, -10, 10] in any order |
| 49 | + System.out.println("actualOutput " + output); |
| 50 | + } |
| 51 | +} |
0 commit comments