leetcode282 : Expression Add Operators
2015-10-15 14:51
501 查看
1、原题如下:
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 -> []
2、解题如下:
3、总结
这道题主要用的是dfs深度检索,遍历所有可能出现的情况。其实我们设想,如果num.size()为9,那就相当于有八个地方可以添加符号,我们可以选择填或者不填,虽然每两个数之间只能填一个操作符,但是总共填多少个并不限制,如此就会有很多种情况。point1之前首先确定第一个操作数,至于它到底有几位,我们根据循环来逐次遍历。然后启动dfs遍历功能,然后循环迭代,考虑下一个添加符号的位置在哪里(还是逐次遍历)操作完所有数之后就进行判断,看是否计算结果符合,符合就插入,不符合就继续之前的dfs~
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 -> []
2、解题如下:
class Solution { public: void dfs(vector<string>& result, const string num, const int target, int pos, string os, const long calres, const char lo, const long ln) { if (pos == num.size() && calres == target) result.push_back(os); else { for (int i = pos + 1; i <= num.size(); i++) { string nos = num.substr(pos, i - pos); long nol = stol(nos); if (to_string(nol).size() != i - pos) continue; dfs(result, num, target, i, os + '+' + nos, calres + nol, '+', nol); dfs(result, num, target, i, os + '-' + nos, calres - nol, '-', nol); dfs(result, num, target, i, os + '*' + nos, (lo == '+') ? (calres - ln + ln*nol) : (lo == '-') ? (calres + ln - ln*nol) : ln*nol, lo, ln*nol); } } } //fos:first operational string //fol:first operational long //nos:next operational string //nol:next operational long //lo:last operator //ln:last number vector<string> addOperators(string num, int target) { vector<string> result; if (!num.size()) return result; for (int i = 1; i <= num.size(); i++) { string fos = num.substr(0, i);//切割出第一个操作数 long fol = stol(fos); if (to_string(fol).size() != i) continue; dfs(result, num, target, i, fos, fol, ' ', fol);//(point1) } return result; } };
3、总结
这道题主要用的是dfs深度检索,遍历所有可能出现的情况。其实我们设想,如果num.size()为9,那就相当于有八个地方可以添加符号,我们可以选择填或者不填,虽然每两个数之间只能填一个操作符,但是总共填多少个并不限制,如此就会有很多种情况。point1之前首先确定第一个操作数,至于它到底有几位,我们根据循环来逐次遍历。然后启动dfs遍历功能,然后循环迭代,考虑下一个添加符号的位置在哪里(还是逐次遍历)操作完所有数之后就进行判断,看是否计算结果符合,符合就插入,不符合就继续之前的dfs~
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android之获取手机上的图片和视频缩略图thumbnails
- android string.xml文件中的整型和string型代替
- Android java 与 javascript互访(相互调用)的方法例子
- 关于指针的一些事情
- android上改变listView的选中颜色
- String.intern
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- 只有程序员看的懂的面试圣经|如何拿下编程面试
- 下一次技术面试时要问的 3 个重要问题
- Prototype源码浅析 String部分(二)
- Ruby中的String对象学习笔记
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- PostgreSQL ERROR: invalid escape string 解决办法
- PHP程序员面试 切忌急功近利(更需要注重以后的发展)
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏