添加运算符-LintCode
来源:互联网 发布:世界银行拨款数据 编辑:程序博客网 时间:2024/06/05 04:29
给定一个仅包含数字 0 - 9 的字符串和一个目标值,返回在数字之间添加了 二元 运算符(不是一元)+, - 或 * 之后所有能得到目标值的情况。
样例:
"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 -> []
#ifndef C653_H#define C653_H#include<iostream>#include<string>#include<vector>using namespace std;class Solution {public: /* * @param num: a string contains only digits 0-9 * @param target: An integer * @return: return all possibilities */ vector<string> addOperators(string &num, int target) { // write your code here vector<string> res; if (num.empty()) return res; vector<string> dic{ "+", "-", "*" }; string str; helper(num, str, target, 0, 0, 0, res); return res; } /* str表示添加了运算符的字符串,pos表示当前位置, * curVal,preVal分别表示当前字符串运算的总和,上一步运算得到的值 * n表示当前的数字,当运算符是加号,当前字符串运算的总和就是之前的总和加上当前数字,将本次得到的数字值置为上一步运算得到的值 * 当运算符是乘号,需要减去上一步的值再加上上一步值与n的乘积 */ void helper(string num, string str, int target, int pos, long long curVal, long long preVal, vector<string> &res) { if (pos == num.size()&&curVal==target) { res.push_back(str); return; } for (int i = pos + 1; i <= num.size(); ++i) { string tmp = num.substr(pos,i-pos); long long n = stoll(tmp); if (tmp[0] == '0'&&tmp.size() > 1) break; if (pos == 0) helper(num, tmp, target, i, n, n, res); else { helper(num, str + "+" + tmp, target, i, curVal + n, n, res); helper(num, str + "-" + tmp, target, i, curVal - n, -n, res); helper(num, str + "*" + tmp, target, i, curVal - preVal + preVal*n, preVal*n, res); } } }};#endif
阅读全文
0 0
- 添加运算符-LintCode
- Lintcode运算符重载
- LintCode-赋值运算符重载
- LintCode-赋值运算符重载
- lintcode-赋值运算符重载
- 赋值运算符重载-LintCode
- LintCode-剑指Offer-(208)赋值运算符重载
- LintCode位运算题总结
- LintCode-第一题:A+B problem (不用“+”等运算符)(位运算实现加法)
- 题目1:添加赋值运算符函数
- LintCode A + B 问题 : 理解不使用运算符计算加乘
- lintcode刷题 A + B 问题 位运算
- 【lintcode】1、A+B问题【位运算】
- [LintCode]1.A + B 问题 位运算
- lintcode天梯4- 数学与二进制运算
- Lintcode 单词的添加与查找
- 单词的添加与查找-LintCode
- lintcode 给出两个整数a和b, 求他们的和, 但不能使用 + 等数学运算符。
- dex文件与class文件如何生成
- Android的开发之&java23中设计模式------>抽象工厂模式
- 时钟
- 使用source命令的时候提示source: command not found错误解决
- 线程的同步问题
- 添加运算符-LintCode
- scala
- 欢迎使用CSDN-markdown编辑器
- 为什么实体类需要序列化
- angularJs路由小Demo
- Eclipse Memory Analyzer
- SSH无密钥登陆 与 配置公钥后仍需要输入密码的解决方案
- JVM详解
- 线程并发二:线程基本操作