Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +-, or *between the digits so they evaluate to the target value.

Example 1:

Input: num = "123", target = 6
Output: ["1+2+3", "1*2*3"]

Example 2:

Input: num = "232", target = 8
Output: ["2*3+2", "2+3*2"]

Example 3:

Input: num = "105", target = 5
Output: ["1*0+5","10-5"]

Example 4:

Input: num = "00", target = 0
Output: ["0+0", "0-0", "0*0"]

Example 5:

Input: num = "3456237490", target = 9191
Output: []

给一个只由数字组成的字符串,在数字之间添加+,-或*号来组成一个表达式,使得该表达式的计算结果为给定了target值,找出所有符合要求的表达式。

解法:递归

This problem has a lot of edge cases to be considered:

overflow: we use a long type once it is larger than Integer.MAX_VALUE or minimum, we get over it.
0 sequence: because we can't have numbers with multiple digits started with zero, we have to deal with it too.
a little trick is that we should save the value that is to be multiplied in the next recursion.

Java:

public class Solution {
public List<String> addOperators(String num, int target) {
List<String> rst = new ArrayList<String>();
if(num == null || num.length() == 0) return rst;
helper(rst, "", num, target, 0, 0, 0);
return rst;
}
public void helper(List<String> rst, String path, String num, int target, int pos, long eval, long multed){
if(pos == num.length()){
if(target == eval)
rst.add(path);
return;
}
for(int i = pos; i < num.length(); i++){
if(i != pos && num.charAt(pos) == '0') break;
long cur = Long.parseLong(num.substring(pos, i + 1));
if(pos == 0){
helper(rst, path + cur, num, target, i + 1, cur, cur);
}
else{
helper(rst, path + "+" + cur, num, target, i + 1, eval + cur , cur); helper(rst, path + "-" + cur, num, target, i + 1, eval -cur, -cur); helper(rst, path + "*" + cur, num, target, i + 1, eval - multed + multed * cur, multed * cur );
}
}
}
}  

Python:

class Solution(object):
def addOperators(self, num, target):
"""
:type num: str
:type target: int
:rtype: List[str]
"""
result, expr = [], []
val, i = 0, 0
val_str = ""
while i < len(num):
val = val * 10 + ord(num[i]) - ord('0')
val_str += num[i]
# Avoid "00...".
if str(val) != val_str:
break
expr.append(val_str)
self.addOperatorsDFS(num, target, i + 1, 0, val, expr, result)
expr.pop()
i += 1
return result def addOperatorsDFS(self, num, target, pos, operand1, operand2, expr, result):
if pos == len(num) and operand1 + operand2 == target:
result.append("".join(expr))
else:
val, i = 0, pos
val_str = ""
while i < len(num):
val = val * 10 + ord(num[i]) - ord('0')
val_str += num[i]
# Avoid "00...".
if str(val) != val_str:
break # Case '+':
expr.append("+" + val_str)
self.addOperatorsDFS(num, target, i + 1, operand1 + operand2, val, expr, result)
expr.pop() # Case '-':
expr.append("-" + val_str)
self.addOperatorsDFS(num, target, i + 1, operand1 + operand2, -val, expr, result)
expr.pop() # Case '*':
expr.append("*" + val_str)
self.addOperatorsDFS(num, target, i + 1, operand1, operand2 * val, expr, result)
expr.pop() i += 1  

C++:

class Solution {
public:
vector<string> addOperators(string num, int target) {
vector<string> res;
addOperatorsDFS(num, target, 0, 0, "", res);
return res;
}
void addOperatorsDFS(string num, int target, long long diff, long long curNum, string out, vector<string> &res) {
if (num.size() == 0 && curNum == target) {
res.push_back(out);
}
for (int i = 1; i <= num.size(); ++i) {
string cur = num.substr(0, i);
if (cur.size() > 1 && cur[0] == '0') return;
string next = num.substr(i);
if (out.size() > 0) {
addOperatorsDFS(next, target, stoll(cur), curNum + stoll(cur), out + "+" + cur, res);
addOperatorsDFS(next, target, -stoll(cur), curNum - stoll(cur), out + "-" + cur, res);
addOperatorsDFS(next, target, diff * stoll(cur), (curNum - diff) + diff * stoll(cur), out + "*" + cur, res);
} else {
addOperatorsDFS(next, target, stoll(cur), stoll(cur), cur, res);
}
}
}
};

  

类似题目:

[LeetCode] 40. Combination Sum II 组合之和 II

[LeetCode] 224. Basic Calculator 基本计算器

[LeetCode] 494. Target Sum 目标和

All LeetCode Questions List 题目汇总

[LeetCode] 282. Expression Add Operators 表达式增加操作符的更多相关文章

  1. [LeetCode] Expression Add Operators 表达式增加操作符

    Given a string that contains only digits 0-9 and a target value, return all possibilities to add ope ...

  2. [leetcode]282. Expression Add Operators 表达式添加运算符

    Given a string that contains only digits 0-9 and a target value, return all possibilities to add bin ...

  3. LeetCode 282. Expression Add Operators

    原题链接在这里:https://leetcode.com/problems/expression-add-operators/ 题目: Given a string that contains onl ...

  4. 282 Expression Add Operators 给表达式添加运算符

    给定一个仅包含0-9的字符串和一个目标值,返回在数字之间添加了二元运算符(不是一元的) +.-或*之后所有能得到目标值的情况.例如:"123", 6 -> ["1+ ...

  5. 【LeetCode】282. Expression Add Operators

    题目: Given a string that contains only digits 0-9 and a target value, return all possibilities to add ...

  6. 282. Expression Add Operators

    题目: Given a string that contains only digits 0-9 and a target value, return all possibilities to add ...

  7. [Swift]LeetCode282. 给表达式添加运算符 | Expression Add Operators

    Given a string that contains only digits 0-9 and a target value, return all possibilities to add bin ...

  8. LeetCode Expression Add Operators

    原题链接在这里:https://leetcode.com/problems/expression-add-operators/ 题目: Given a string that contains onl ...

  9. [LeetCode] Ternary Expression Parser 三元表达式解析器

    Given a string representing arbitrarily nested ternary expressions, calculate the result of the expr ...

随机推荐

  1. python测试开发django-rest-framework-61.权限认证(permission)

    前言 用户登录后,才有操作当前用户的权限,不能操作其它人的用户,这就是需要用到权限认证,要不然你登录自己的用户,去操作别人用户的相关数据,就很危险了. authentication是身份认证,判断当前 ...

  2. CentOS 6.x 无法格式化大于16TB的ext4分区处理

    CentOS 6.x 在格式化大于16TB的ext4分区时,会提示如下错误: mke2fs 1.41.12 (17-May-2010) mkfs.ext4: Size of device /dev/s ...

  3. eclipse spring MVC maven项目 maven install target下无war包

    1.排查问题 一步步去看,首先查看本地maven是否安装    命令:ctrl+r   cmd   输入  mvn -v  查看maven版本 2.查看  window>preference  ...

  4. Haskell语言学习笔记(95)Semiring

    semirings 模块 semirings 模块需要安装 $ cabal install semirings Installed semirings-0.2.0.1 Prelude> :m + ...

  5. 应用安全测试技术DAST、SAST、IAST对比分析【转】

    转自:https://blog.csdn.net/qq_29277155/article/details/92411079 一.全球面临软件安全危机 2010年,大型社交网站rockyou.com被曝 ...

  6. Bagging and Random Forest

    Bagging和随机森林RF. 随机森林是最受欢迎和最强大的机器学习算法之一.它是一种称为Bootstrap Aggregation或bagging的集成机器学习算法. bootstrap是一种强大的 ...

  7. 通过redash query results 数据源实现跨数据库的查询

    redash 提供了一个简单的 query results 可以帮助我们进行跨数据源的查询处理 底层数据的存储是基于sqlite的,期望后期有调整(毕竟处理能力有限),同时 query results ...

  8. POJ 1741.Tree and 洛谷 P4178 Tree-树分治(点分治,容斥版) +二分 模板题-区间点对最短距离<=K的点对数量

    POJ 1741. Tree Time Limit: 1000MS   Memory Limit: 30000K Total Submissions: 34141   Accepted: 11420 ...

  9. mysql e的n次幂exp()

    mysql> ); +-------------------+ | exp() | +-------------------+ | 2.718281828459045 | +---------- ...

  10. GIT 使用记录,新手->会用(mac 用户)

    (唔,mac 用户这个要求是因为集成在 terminal 中可直接使用) 1. github 中 创建 git 账户 2. github -> 在个人设置中 找到 ssh  and GPGkey ...