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. django考点答案

    1 列举Http请求中常见的请求方式 2 谈谈你对HTTP协议的认识.1.1 长连接3 简述MVC模式和MVT模式4 简述Django请求生命周期5 简述什么是FBV和CBV6 谈一谈你对ORM的理解 ...

  2. [转载]Fiddler界面详解

    转载地址:http://www.cnblogs.com/chengchengla1990/p/5681775.html Statistics 页签 完整页签如下图: Statistics 页签显示当前 ...

  3. 常用conda命令【转载】

    转载地址:https://haoyu.love/blog900.html 一直在用 Conda,很多东西记不住,每次都要查 Doc.那好,就写在这里做个备忘好了. 在 bash 里面自动加载 cond ...

  4. jquery ajax请求数据超时设置

    var ajaxTimeoutTest = $.ajax({ url:'', //请求的URL timeout : 1000, //超时时间设置,单位毫秒 type : 'get', //请求方式,g ...

  5. 做阉割版Salesforce难成伟大的TOB企业

    https://www.lieyunwang.com/archives/446227 猎云注:当前中国市场环境下,有没有可能诞生一批SaaS级企业服务公司?东方富海合伙人陈利伟用三个方面基础性问题解答 ...

  6. 002_Visual Studio (gnuplot)显示数组波形

    视频教程:https://v.qq.com/x/page/e3039v4j6zs.html 资料下载:https://download.csdn.net/download/xiaoguoge11/12 ...

  7. SQL基础-创建新的输出字段

    一.创建新的输出字段 1.建表.插数据 ### CREATE TABLE `t_stock_trans_dtl` ( `trans_id` varchar(100) NOT NULL COMMENT ...

  8. gulp+webpack多页应用开发,webpack仅处理打包js

    项目背景:一个综合网站,开发模式为后端嵌套数据,前端开发静态页面和部分组件. 问题:gulp任务处理自动刷新.sass编译等都是极好的.但是对于js的处理并不是很好,尤其是项目需要开发组件时候,如评论 ...

  9. 手把手教你用Python代码实现微信聊天机器人 -- Python wxpy

    关注我,每天都有优质技术文章推送,工作,学习累了的时候放松一下自己. 本篇文章同步微信公众号 欢迎大家关注我的微信公众号:「醉翁猫咪」 来学习了,微信聊天机器人. 环境要求: Windows / Li ...

  10. nginx之别名、location使用

    alias server { listen 80; server_name www.xxxpc.net ~^www\.site\d+\.net$; error_page 500 502 503 504 ...