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. Hoax or what UVA - 11136(multiset的应用)

    刚开始把题意理解错了,结果样例没过,后来发现每天只处理最大和最小的,其余的不管,也就是说昨天的元素会影响今天的最大值和最小值,如果模拟的话明显会超时,故用multiset,另外发现rbegin()的功 ...

  2. 最新NetMonitor代码

    <Window x:Class="NetMonitor.MainWindow" xmlns="http://schemas.microsoft.com/winfx/ ...

  3. NumPy的Linalg线性代数库探究

    1.矩阵的行列式 from numpy import * A=mat([[1,2,4,5,7],[9,12,11,8,2],[6,4,3,2,1],[9,1,3,4,5],[0,2,3,4,1]]) ...

  4. python - 手机号正则匹配

    Python 手机号正则匹配 # -*- coding:utf-8 -*- import re def is_phone(phone): phone_pat = re.compile('^(13\d| ...

  5. (nohup+开启fitnesse的命令+&)让fitnesse在linux可脱离终端在后台运行

    1.脱离终端后台运行fitnesse 用终端连接linux时,开启fitnesse命令后,界面是这样的. 如果此时终端关闭或是不小心按了ctrl+c,fitnesse就被关闭,页面就无法访问了 为了解 ...

  6. 23-ESP8266 SDK开发基础入门篇--编写Android TCP客户端 , 加入消息处理

    https://www.cnblogs.com/yangfengwu/p/11203546.html 先做接收消息 然后接着 public class MainActivity extends App ...

  7. CSS3 之书页阴影效果

    视觉如下: CSS3 之书页阴影效果: <html> <head> <meta charset="UTF-8"> <title>书页 ...

  8. 微信小程序音乐播放器组件

    wxml <image bindtap="click" src="{{isPlay?'/images/':'/images/'}}"/> JS Pa ...

  9. 无法定位程序输入点到xxx.dll

    Q:安装pytorch时报错无法定位程序输入点到Anaconda3\Library\bin\libssl-1_1-x64.dll A:下载libssl-1_1-x64.dll覆盖bin下的文件 下载地 ...

  10. SDN第七次上机作业

    1.补充并运行basic代码 任务是实现基础的交换机转发数据包功能 补充后代码如下: /* -*- P4_16 -*- */ #include <core.p4> #include < ...