当前位置:网站首页>[daily question] 241 Design priorities for operational expressions
[daily question] 241 Design priorities for operational expressions
2022-07-02 19:51:00 【Wang Liuliu's it daily】
241. Design priorities for operation expressions
Refer to the explanation of the question :https://leetcode.cn/problems/different-ways-to-add-parentheses/solution/wei-yun-suan-biao-da-shi-she-by-jiang-hu-0pf0/
- recursive
Follow the string as The operator Split into two sub expressions , The result set of the two sub expressions is currently op The operation of , Assemble into a new result set , For each op The final answer is the sum of the result sets obtained by segmentation respectively . And the subexpression is the same problem , May adopt recursive Calculate , It will eventually recurse to a digit On .
class Solution {
public List<Integer> diffWaysToCompute(String expression) {
// The expression is empty
if (expression == null || expression.length() == 0) {
return new ArrayList<>();
}
char[] chars = expression.toCharArray();
List<Integer> ans = new ArrayList<>();
for (int i = 0; i < chars.length; i++) {
char aChar = chars[i];
// If the current character is an operator , That is to say op, Segmentation
if (!Character.isDigit(aChar)) {
// Recursively get the result set of the left and right expressions
List<Integer> leftList = diffWaysToCompute(expression.substring(0, i));
List<Integer> rightList = diffWaysToCompute(expression.substring(i + 1));
// All the results of the two result sets are op operation
for (Integer left : leftList) {
for (Integer right : rightList) {
if (aChar == '+') {
ans.add(left + right);
} else if (aChar == '-') {
ans.add(left - right);
} else {
ans.add(left * right);
}
}
}
}
}
// Result set is empty , Prove that the string is a number , Add numbers to the result set
if (ans.isEmpty()) {
ans.add(Integer.valueOf(expression));
}
return ans;
}
}
- Dynamic programming
Because the final answer is a sub question ( subexpression ) The answer of , Therefore, dynamic programming can be adopted , Divide the problem into a sub problem to solve .
First, we divide the string into digit、op、digit、op、digit、op、digit… This sequence , And we know that the length of the sequence is an odd number , So the minimum length of the subproblem is 3( The length is 1 Of digit There is no need to calculate ), That's one op The operation requires at least three elements ( Two digit And a op), The length of the next sub problem is the current sub problem +2( Add one more op And a digit), So we can start from the minimum length of 3 Solve the maximum length solution step by step .
class Solution {
public List<Integer> diffWaysToCompute(String expression) {
List<Object> ops = new ArrayList<>();
// Split string into digit、op、digit、op、digit...... This sequence
for (int i = 0; i < expression.length(); ) {
if (!Character.isDigit(expression.charAt(i))) {
// Add operator
ops.add(expression.charAt(i));
i++;
} else {
// Add numbers
int digit = 0;
while (i < expression.length() && Character.isDigit(expression.charAt(i))) {
digit = digit * 10 + expression.charAt(i) - '0';
i++;
}
ops.add(digit);
}
}
//dp[i][j] From i To j Sub problem ( subexpression ) All the answers
List<Integer>[][] dp = new List[ops.size()][ops.size()];
for (int i = 0; i < ops.size(); i++) {
for (int j = 0; j < ops.size(); j++) {
dp[i][j] = new ArrayList<>();
}
}
// At the beginning , be-all digit They are themselves and the numbers are stored across , And the position is fixed in even digits (0,2,4...) therefore +2
//eg:digit、op、digit、op、digit......
for (int i = 0; i < ops.size(); i += 2) {
dp[i][i].add((int) ops.get(i));
}
// From the length to 3 Start to calculate the subproblem of
for (int len = 3; len <= ops.size(); len += 2) {
// The left boundary starts from 0 Start
for (int left = 0; left + len <= ops.size(); left += 2) {
// Right border
int right = left + len - 1;
// according to op Split the left and right sub expressions +2 It means next op
for (int k = left + 1; k < right; k += 2) {
List<Integer> leftAns = dp[left][k - 1];
List<Integer> rightAns = dp[k + 1][right];
// Merge the result sets of the left and right sub expressions
for (int num1 : leftAns) {
for (int num2 : rightAns) {
char op = (char) ops.get(k);
if (op == '+') {
dp[left][right].add(num1 + num2);
} else if (op == '-') {
dp[left][right].add(num1 - num2);
} else if (op == '*') {
dp[left][right].add(num1 * num2);
}
}
}
}
}
}
return dp[0][ops.size() - 1];
}
}
- DFS
Reference resources :https://leetcode.cn/problems/different-ways-to-add-parentheses/solution/by-ac_oier-z07i/
class Solution {
char[] cs;
public List<Integer> diffWaysToCompute(String s) {
cs = s.toCharArray();
return dfs(0, cs.length - 1);
}
List<Integer> dfs(int l, int r) {
List<Integer> ans = new ArrayList<>();
for (int i = l; i <= r; i++) {
if (cs[i] >= '0' && cs[i] <= '9') continue;
List<Integer> l1 = dfs(l, i - 1), l2 = dfs(i + 1, r);
for (int a : l1) {
for (int b : l2) {
int cur = 0;
if (cs[i] == '+') cur = a + b;
else if (cs[i] == '-') cur = a - b;
else cur = a * b;
ans.add(cur);
}
}
}
if (ans.isEmpty()) {
int cur = 0;
for (int i = l; i <= r; i++) cur = cur * 10 + (cs[i] - '0');
ans.add(cur);
}
return ans;
}
}
边栏推荐
猜你喜欢
Kt148a voice chip instructions, hardware, protocols, common problems, and reference codes
AcWing 340. 通信线路 题解(二分+双端队列BFS求最短路)
Educational Codeforces Round 129 (Rated for Div. 2) 补题题解
Detailed tutorial on installing stand-alone redis
Py之interpret:interpret的简介、安装、案例应用之详细攻略
KT148A语音芯片ic的用户端自己更换语音的方法,上位机
蓝牙芯片ble是什么,以及该如何选型,后续技术发展的路径是什么
数据湖(十二):Spark3.1.2与Iceberg0.12.1整合
Motivation! Big Liangshan boy a remporté le prix Zhibo! Un article de remerciement pour les internautes qui pleurent
Conscience summary! Jupyter notebook from Xiaobai to master, the nanny tutorial is coming!
随机推荐
AcWing 1135. 新年好 题解(最短路+搜索)
How to avoid duplicate data in gaobingfa?
Windows2008r2 installing php7.4.30 requires localsystem to start the application pool, otherwise 500 error fastcgi process exits unexpectedly
Shardingsphere jdbc5.1.2 about select last_ INSERT_ ID () I found that there was still a routing problem
HDL design peripheral tools to reduce errors and help you take off!
Codeworks round 802 (Div. 2) pure supplementary questions
upload-labs
B端电商-订单逆向流程
安装单机redis详细教程
《MongoDB入门教程》第03篇 MongoDB基本概念
AcWing 1135. Happy New Year (shortest path + search)
AcWing 383. 观光 题解(最短路)
RPD product: super power squad nanny strategy
Think about the huge changes caused by variables
Registration opportunity of autowiredannotationbeanpostprocessor under annotation development mode
Golang concurrent programming goroutine, channel, sync
AcWing 1134. 最短路计数 题解(最短路)
中缀表达式转换为后缀表达式(C语言代码+详解)
ShardingSphere-JDBC5.1.2版本关于SELECT LAST_INSERT_ID()本人发现还是存在路由问题
JS如何取整数