lintcode(653)Add Operators
来源:互联网 发布:学车电销数据 编辑:程序博客网 时间:2024/06/07 12:44
Description:
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.
Explanation:
"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 -> []
Solution:
DFS(Depth-first-search).
找出所有可能的情况,涉及到多种组合方式,对每一条分支(组合方式)都要进行深度搜索,直至不能深入,所以采用深度优先搜索。
首先建立一个list来存储结果。建立dfs函数来搜索所有情况。搜索过程中先截取字符串,作为当前操作的数值,然后分别匹配+ - * 三种运算,要注意计算的优先级,所以计算乘法时,要回溯。其次要注意特殊情况,0可以单独作为操作数,但是不可以在多位数中占首位;第一次计算时,当前表达式为空,前边不添加计算符。
public class Solution { /** * @param num a string contains only digits 0-9 * @param target an integer * @return return all possibilities * Author:Sunday0904 */ ArrayList<String> result = new ArrayList<String>(); public List<String> addOperators(String num, int target) { // Write your code here DFS(num , target , "" , 0 , 0); return result; } public void DFS(String num , int target , String temp , long curResult , long preNum){ if(curResult == target && num.length() == 0){ String expression = new String(temp); result.add(expression); return ; } for(int i = 1;i<=num.length();i++){ String curStr = num.substring(0 , i); if(curStr.length() > 1 && curStr.startsWith("0")){ return ; } String newNum = num.substring(i); long curNum = Long.parseLong(curStr); if(temp.length() == 0){ DFS(newNum , target , curStr , curNum , curNum); }else{ DFS(newNum , target , temp + "+" + curStr , curResult + curNum , curNum); DFS(newNum , target , temp + "-" + curStr , curResult - curNum , -curNum); DFS(newNum , target , temp + "*" + curStr , curResult - preNum + preNum * curNum , preNum * curNum); } } }}
阅读全文
0 0
- lintcode(653)Add Operators
- LINTCODE——Add Operators
- LeetCode:Expression Add Operators
- 【LeetCode】Expression Add Operators
- Expression Add Operators【282】
- Expression Add Operators
- Expression Add Operators
- Expression Add Operators
- Expression Add Operators -- leetcode
- leetcode282 : Expression Add Operators
- Leetcode -- Expression Add Operators
- LeetCode -- Expression Add Operators
- LeetCode Expression Add Operators
- Expression Add Operators
- leetcode:Expression Add Operators
- 282. Expression Add Operators
- Expression Add Operators
- 282. Expression Add Operators
- 第一课 JSON的简介
- React Native集成到IOS原生项目
- nginx+php显示 502 bad gateway的解决方法
- Java单例模式——暂时完美的单例
- EventBus使用详解(一)——初步使用EventBus
- lintcode(653)Add Operators
- codeforces 472A Design Tutorial: Learn from Math
- Spring(一)概况
- SDOI2013 森林
- 【Android】【Framework】MessageQueue
- 根据OLAMI平台开发的日历Demo
- 正则表达式
- Vue中的$set的使用
- 网址收藏