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 }

使用分治的思想。

 

转载于:https://www.cnblogs.com/guoguolan/p/5619922.html

在使用 `env.py` 时,如果遇到 `Missing parentheses in call to 'print'` 错误,这通常是由于代码中使用了 Python 2 的 `print` 语法,而当前运行环境是 Python 3。Python 3 中的 `print` 是一个函数,因此必须使用括号来包裹输出内容。 例如,Python 2 中的写法: ```python print "Hello, world!" ``` 在 Python 3 中应该改为: ```python print("Hello, world!") ``` ### 解决方法 1. **修改 `env.py` 文件中的 `print` 语句** 找到文件中所有未使用括号的 `print` 语句,并将其更改为函数调用形式。例如,将: ```python print readerRef ``` 改为: ```python print(readerRef) ``` [^1] 2. **检查文件中的所有 `print` 语句** 确保文件中所有 `print` 语句都符合 Python 3 的语法要求,避免遗漏。例如: ```python print "Cannot run setup when server is running." ``` 应该修改为: ```python print("Cannot run setup when server is running.") ``` [^3] 3. **确认运行环境的 Python 版本** 如果项目原本是为 Python 2 编写的,建议检查所有依赖库是否兼容 Python 3。如果不兼容,可以考虑使用虚拟环境运行 Python 2,或者对代码进行迁移以适配 Python 3。 4. **使用自动化工具进行语法转换** 可以使用 `2to3` 工具自动将 Python 2 代码转换为 Python 3 代码。例如: ```bash 2to3 -w env.py ``` 这将自动修复 `print` 语句等不兼容问题。 5. **确保文件具有可执行权限(如涉及脚本执行)** 如果 `env.py` 是一个可执行脚本,确保它具有正确的执行权限: ```bash chmod +x env.py ``` 此外,检查文件的第一行是否指定了正确的解释器,例如: ```python #!/usr/bin/env python3 ``` 通过以上方法,可以有效解决 `env.py` 中出现的 `Missing parentheses in call to 'print'` 错误。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值