《leetcode》:Expression Add Operators
来源:互联网 发布:大屏数据 编辑:程序博客网 时间:2024/05/29 10:49
题目
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.
Examples: "123", 6 -> ["1+2+3", "1*2*3"] "232", 8 -> ["2*3+2", "2+3*2"] "105", 5 -> ["1*0+5","10-5"] "00", 0 -> ["0+0", "0-0", "0*0"] "3456237490", 9191 -> []
思路
此题比较难,不太好想,自己在看到这个题目的时候也感觉算法思想应该是这么来做,但是就是不太清晰,不知道应该怎么来写代码来实现。
参考于这里:https://discuss.leetcode.com/topic/24523/java-standard-backtrace-ac-solutoin-short-and-clear/2
实现代码如下:
public class Solution { private String num; private int target; public List<String> addOperators(String num, int target) { List<String> res = new ArrayList<String>(); int len = num.length(); if(len==0){ return res; } this.num = num; this.target = target; addOperatorsHelper(res,"",0,0,0); return res; } private void addOperatorsHelper(List<String> res, String path, int pos, long eval, long mult) { if(pos==this.num.length()){ if(eval==this.target){ res.add(path); } return; } for(int i=pos;i<this.num.length();i++){ if(i!=pos&&this.num.charAt(pos)=='0'){//多位数的第一位数不能为0 break; } Long cur = Long.parseLong(this.num.substring(pos, i+1)); if(pos==0){ addOperatorsHelper(res,path+cur,i+1,cur,cur); } else{ addOperatorsHelper(res,path+"+"+cur,i+1,eval+cur,cur); addOperatorsHelper(res,path+"-"+cur,i+1,eval-cur,-cur);//注意这里是负cur addOperatorsHelper(res,path+"*"+cur,i+1,eval-mult+cur*mult,cur*mult); } } } }
0 0
- LeetCode:Expression Add Operators
- 【LeetCode】Expression Add Operators
- Expression Add Operators -- leetcode
- Leetcode -- Expression Add Operators
- LeetCode -- Expression Add Operators
- LeetCode Expression Add Operators
- leetcode:Expression Add Operators
- 《leetcode》:Expression Add Operators
- [leetCode] Expression Add Operators
- [LeetCode]Expression Add Operators
- [LeetCode] Expression Add Operators
- 【LeetCode】Expression Add Operators
- Expression Add Operators(leetcode)
- Leetcode | Expression Add Operators
- [leetcode 282]Expression Add Operators
- [leetcode] 282. Expression Add Operators
- [LeetCode]282. Expression Add Operators
- leetcode(282): Expression Add Operators
- 底部Tab栏的实现(附完整代码)
- hdoj1715大菲波数(大数+打表,大数斐波那契数列)
- kvo,kvc
- C/C++笔记(C语言重要问题重讲,内存四区篇)
- 分享一个php时间段切分为指定段的函数
- 《leetcode》:Expression Add Operators
- node.js之Promise初见
- 2016微软探星夏令营:#1341 : Constraint Checker
- 简单handler实现闪屏页面跳转
- 初识Elasticsearch搜索引擎
- [HDU 5408] CRB and Farm (几何+凸包)
- Androida百度地图开发之显示百度地图
- 《leetcode》:Perfect Squares
- linux文本处理三剑客(二):sed命令详解