LeetCode:Expression Add Operators
2015-09-22 11:24
411 查看
题目链接:https://leetcode.com/problems/expression-add-operators/、
题目:
Given a string that contains only digits
possibilities to add binaryoperators (not unary)
or
Examples:
题意:给定一个包含0-9的字符串和一个目标值,返回对字符串中字符的所有可能的运算来得到目标值
方法:递归
注意:在运算乘法时应该将前一步运算移除
题目:
Given a string that contains only digits
0-9and a target value, return all
possibilities to add binaryoperators (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 -> []
题意:给定一个包含0-9的字符串和一个目标值,返回对字符串中字符的所有可能的运算来得到目标值
方法:递归
注意:在运算乘法时应该将前一步运算移除
public class Solution { public List<String> addOperators(String num, int target) { List<String> result = new ArrayList<String>(); addOperatorsDFS(num, target, 0, 0, "", result); return result; } public void addOperatorsDFS(String num, int target, long diff, long curNum, String out, List<String> result) { if(num.length() == 0 && curNum == target) { result.add(out); } for(int i=1; i<=num.length(); i++) { String cur = num.substring(0,i); if(cur.length() > 1 && cur.charAt(0) == '0') return; String next = num.substring(i); if(out.length() > 0) { addOperatorsDFS(next, target, Long.parseLong(cur), curNum + Long.parseLong(cur), out+"+"+cur, result); addOperatorsDFS(next, target, -Long.parseLong(cur), curNum - Long.parseLong(cur), out+"-"+cur, result); addOperatorsDFS(next, target, diff*Long.parseLong(cur), curNum - diff + diff*Long.parseLong(cur), out+"*"+cur, result); } else { addOperatorsDFS(next, target, Long.parseLong(cur), Long.parseLong(cur), cur, result); } } } }
相关文章推荐
- linux学习积累(一) Linux命令之dos2unix
- linux-Kali安装VMware tool@VMware11
- 设置TOMCAT启用GZIP压缩
- linux sort 用法
- linux之ps命令详解
- 关于Ubuntu 9.1 Server 自带安装的Tomcat + Java 命令
- 10 条真心有趣的 Linux 命令
- Quartz2-Quartz与tomcat集成
- Linux 下 mysql 的相关命令
- Linux下C高手成长过程----经典书籍推荐
- MapReduce V2---Yarn的架构及其执行原理
- getopt— C-style parser for command line options
- 省市联动 DropDownList控件
- Ubuntu Server9 + Tomcat + mysql + Jdk 安装后遇到的一些常见问题
- CentOS 7 之 hostapd AP模式配置
- Linux Root下的.gvfs出现异常解决办法(导致source失败,自启动失败)
- Linux Shell 命令 简介
- 常用linux命令(跟大神学的)
- CentOS 7 之 hostapd.conf 配置说明
- Linux学习笔记