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]
这道题就是考察添加括号,最初的想法是中序转后序,然后判定优先级来做。
后来网上看到了一个超级棒的做法。
建议直接看C++的这做法,这道题十分的棒,直接递归即可
强烈建议和leetcode 95. Unique Binary Search Trees II 递归构造所有可能的搜索二叉树BST + 卡特兰数 和 leetcode 96. Unique Binary Search Trees 卡特兰数:BST的数量 + 栈出栈数量 一起学习,它们的做法很相识,值得放在一起学习
还有这一道题leetcode 282. Expression Add Operators 任意添加运算符计算结果 +深度优先遍历DFS
代码如下:
import java.util.ArrayList;
import java.util.List;
/*
* 亏我还一直想着中序转后序,然后判定不同的优先级去做计算
* 这个题的思路就是针对每一个运算符去递归去做计算
*
* 首先是基本的递归的思想,从前往后遍历,
* 对于每一个运算符将其左右子字符串分成两部分,
* 然后计算两边的各种不同的结果来,然后和在一起,
* 这中间不存是不存在加括号的相同发的情况的。
*
* */
public class Solution
{
public List<Integer> diffWaysToCompute(String input)
{
List<Integer> res=new ArrayList<Integer>();
for(int i=0;i<input.length();i++)
{
char one=input.charAt(i);
if(one=='-' || one=='+' || one=='*')
{
List<Integer> left = diffWaysToCompute(input.substring(0,i));
List<Integer> right = diffWaysToCompute(input.substring(i+1));
for(int k=0;k<left.size();k++)
{
for(int j=0;j<right.size();j++)
{
if(one=='-')
res.add(left.get(k)-right.get(j));
else if(one=='+')
res.add(left.get(k)+right.get(j));
else
res.add(left.get(k)*right.get(j));
}
}
}
}
if(res.isEmpty())
res.add(Integer.parseInt(input));
return res;
}
}
下面是C++的做法,就是做一个DFS遍历,这道题其实很难想到这么做。所以很值得学习
代码如下:
#include <iostream>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <functional>
#include <bitset>
#include <numeric>
#include <cmath>
#include <regex>
using namespace std;
class Solution
{
public:
vector<int> diffWaysToCompute(string input)
{
vector<int> res;
if (input.length()<=0 || isNum(input) == true)
res.push_back(stoi(input));
else
{
for (int i = 0; i < input.length(); i++)
{
char c = input[i];
if (c == '+' || c == '-' || c == '*')
{
vector<int> left = diffWaysToCompute(input.substr(0, i));
vector<int> right = diffWaysToCompute(input.substr(i+1));
for (int l : left)
{
for (int r : right)
{
if (c == '+')
res.push_back(l + r);
else if (c == '-')
res.push_back(l - r);
else if (c == '*')
res.push_back(l * r);
}
}
}
}
}
return res;
}
bool isNum(string s)
{
for (char c : s)
{
if (c < '0' || c > '9')
return false;
}
return true;
}
};