Skip to main content
Back to problems
#241
Medium Algorithms

Different ways to add parentheses

Math String Dynamic Programming Recursion Memoization
73.1% acceptance
Jan 12, 2026
6314
398
Given a string expression of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. You may return the answer in any order. The test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed 104.

Solution

Rust
Time O(n³)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn diff_ways_to_compute(expression: String) -> Vec<i32> {
    let mut result = Vec::new();
    
    for (i, ch) in expression.chars().enumerate() {
      if ch == '+' || ch == '-' || ch == '*' {
        let left = Self::diff_ways_to_compute(expression[..i].to_string());
        let right = Self::diff_ways_to_compute(expression[i+1..].to_string());
        
        for &l in &left {
          for &r in &right {
            match ch {
              '+' => result.push(l + r),
              '-' => result.push(l - r),
              '*' => result.push(l * r),
              _ => {}
            }
          }
        }
      }
    }
    
    if result.is_empty() {
      result.push(expression.parse().unwrap());
    }
    
    result
  }
}