当前位置:网站首页>241. Design priority for operational expressions: DFS application questions
241. Design priority for operational expressions: DFS application questions
2022-07-01 11:36:00 【Gong Shui Sanye's Diary of writing questions】
Title Description
This is a LeetCode Upper 241. Design priorities for operation expressions , The difficulty is secondary .
Tag : 「DFS」、「 Explosive search 」
Give you a string of numbers and operators expression, Combine numbers and operators according to different priorities , Calculate and return the results of all possible combinations . You can In any order Return to the answer .
The generated test case meets its corresponding output value in line with Bit integer range , The number of different results does not exceed .
Example 1:
Input :expression = "2-1-1"
Output :[0,2]
explain :
((2-1)-1) = 0
(2-(1-1)) = 2
Example 2:
Input :expression = "2*3-4*5"
Output :[-34,-14,-10,-10,10]
explain :
(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
Tips :
expressionBy numbers and operators'+'、'-'and'*'form .All integer values in the input expression are in the range
DFS
For convenience , We make expression by s.
The data range is , And all the calculation results should be counted , We can use DFS Search all plans .
A given s Only numbers and operators , We can divide the formula into left and right parts according to the operator , Design recursive functions List<Integer> dfs(int l, int r), It means to search the substring All operation results of .
The final answer is dfs(0,n-1), among Is the length of the input parameter string , At the same time, we have an obvious recursive exit : When given When there are no operators , The search result is The number itself .
Consider how to treat any Calculate : We can enumerate All operator positions in the range are searched , Suppose the currently enumerated For operator , We can recurse to the left of the operator dfs(l,i-1) Get all the results on the left , To the right of the recursive operator dfs(i+1,r) Get all the results on the right , combination 「 Multiplication principle 」 You can know that with the current operator All schemes of expressions for split points .
It's not hard to find out , All the above processes are made by 「 Small expression 」 The results are derived 「 Large expression 」 Result , So it can also be used 「 Section DP」 Method to solve , Complexity and DFS Agreement .
Code :
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;
}
}
Time complexity : The complexity is related to the number of final results , The number of final results is 「 Carter LAN number 」, The complexity is Spatial complexity : The complexity is related to the number of final results , The number of final results is 「 Carter LAN number 」, The complexity is
Last
This is us. 「 Brush through LeetCode」 The first of the series No.241 piece , The series begins with 2021/01/01, As of the start date LeetCode I have in common 1916 questions , Part of it is a locked question , We will finish all the questions without lock first .
In this series , In addition to explaining the idea of solving problems , And give the most concise code possible . If the general solution is involved, there will be corresponding code templates .
In order to facilitate the students to debug and submit code on the computer , I've built a warehouse :https://github.com/SharingSource/LogicStack-LeetCode .
In the warehouse address , You can see the links to the series 、 The corresponding code of the series 、LeetCode Links to the original problem and other preferred solutions .
More, more, more popular 「 written examination / interview 」 Relevant information can be found in the beautifully arranged Gather new bases
边栏推荐
- Activity workflow engine
- 田溯宁投的天润云上市:市值22亿港元 年利润下降75%
- Is it safe for Huatai Securities to open an account online?
- TEMPEST HDMI泄漏接收 4
- How to make the development of liquidity pledge mining system, case analysis and source code of DAPP defi NFT LP liquidity pledge mining system development
- Value/string in redis
- Redis configuration environment variables
- Jd.com renewed its cooperation with Tencent: issuing class A shares to Tencent with a maximum value of US $220million
- How to realize the four isolation levels of MySQL (brief)
- 妙啊!MarkBERT
猜你喜欢

Tempest HDMI leak reception 4

Shangtang entered the lifting period: the core management voluntarily banned and strengthened the company's long-term value confidence

Redis的攻击手法

Brief analysis of edgedb architecture

陈珙:微服务,它还那么纯粹吗?

编译调试Net6源码

Y48. Chapter III kubernetes from introduction to mastery -- pod status and probe (21)

Spam filtering challenges

Neo4j 中文开发者月刊 - 202206期

金融壹账通拟7月4日香港上市:2年亏近30亿 市值蒸发超90%
随机推荐
想问问,证券开户有优惠吗手机开户是安全么?
Several cases of index failure
ES6 promise Usage Summary
redis中value/list
CANN算子:利用迭代器高效实现Tensor数据切割分块处理
redis中value/set
Adjacency matrix undirected graph (I) - basic concepts and C language
编译调试Net6源码
sshd_ Discussion on permitrotlogin in config
流动性质押挖矿系统开发如何制作,dapp丨defi丨nft丨lp流动性质押挖矿系统开发案例分析及源码
Mingchuang plans to be listed on July 13: the highest issue price is HK $22.1, and the net profit in a single quarter decreases by 19%
Redis common sense
自定义 grpc 插件
Istio、eBPF 和 RSocket Broker:深入研究服务网格
证券账户销户后果 开户安全吗
MySQL IN 和 NOT IN () 空列表报错
分享psd格式怎么预览的方法和psd文件缩略图插件[通俗易懂]
CAD如何设置标注小数位
ES6 Promise用法小结
Learning summary on June 30, 2022