当前位置:网站首页>[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;
}
}
边栏推荐
- Pytorch版本、CUDA版本与显卡驱动版本的对应关系
- Design and implementation of ks004 based on SSH address book system
- 自动生成VGG图像注释文件
- 在消费互联网时代,诞生了为数不多的头部平台的话
- Overview of browser caching mechanism
- Self-Improvement! Daliangshan boys all award Zhibo! Thank you for your paper
- 有时候只查询一行语句,执行也慢
- AcWing 340. Solution to communication line problem (binary + double ended queue BFS for the shortest circuit)
- 安装单机redis详细教程
- Génération automatique de fichiers d'annotation d'images vgg
猜你喜欢

JASMINER X4 1U深度拆解,揭开高效省电背后的秘密

Overview of browser caching mechanism

Educational codeforces round 129 (rated for Div. 2) supplementary problem solution

Self-Improvement! Daliangshan boys all award Zhibo! Thank you for your paper

ShardingSphere-JDBC5.1.2版本关于SELECT LAST_INSERT_ID()本人发现还是存在路由问题

KT148A语音芯片ic的开发常见问题以及描述

为什么我对流程情有独钟?

Educational Codeforces Round 129 (Rated for Div. 2) 补题题解

《重构:改善既有代码的设计》读书笔记(下)

Automatically generate VGg image annotation file
随机推荐
职场四象限法则:时间管理四象限与职场沟通四象限「建议收藏」
Implementation of 453 ATOI function
KT148A语音芯片使用说明、硬件、以及协议、以及常见问题,和参考代码
AcWing 1135. 新年好 题解(最短路+搜索)
HDL design peripheral tools to reduce errors and help you take off!
KT148A语音芯片ic的软件参考代码C语言,一线串口
搭建主从模式集群redis
AcWing 1131. 拯救大兵瑞恩 题解(最短路)
AcWing 341. Optimal trade solution (shortest path, DP)
Overview of browser caching mechanism
RPD product: super power squad nanny strategy
Introduction to program ape (XII) -- data storage
After writing 100000 lines of code, I sent a long article roast rust
From 20s to 500ms, I used these three methods
Istio deployment: quickly start microservices,
How to avoid duplicate data in gaobingfa?
AcWing 343. 排序 题解(floyd性质实现传递闭包)
嵌入式(PLD) 系列,EPF10K50RC240-3N 可编程逻辑器件
《MongoDB入门教程》第03篇 MongoDB基本概念
简书自动阅读