码迷,mamicode.com
首页 > 其他好文 > 详细

282. Expression Add Operators

时间:2016-08-08 19:29:46      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

解题思路:深搜

遍历所有可能的情况,终止条件为表达式计算的结果等于target。注意,这里要使用long 类型保存整数,否则会溢出。我在vs2013,win32模式下使用long同样不能通过

"3456237490", 9191 -> []

这个案例,改用long long 才可以。

具体解析可以参考文末的这篇文章,讲的很好,主要要注意乘法情况下如何计算表达式的值。

class Solution {
public:

	void compute(vector<string>& result, string exp, string num, long target, long cur_num, long pre_num)
	{

		if (cur_num == target&&num.size()==0)
		{
			result.push_back(exp);
			return;
		}
	
		for (int i = 1; i <= num.size(); i++)
		{
			string curStr = num.substr(0, i);
			if (curStr.size()>1 && curStr[0] == '0')
				return;
			long curTmp = stol(curStr);
			string nextStr = num.substr(i);
			if (exp.size() != 0)
			{
				compute(result,exp+"+"+curStr,nextStr,target,curTmp+cur_num,curTmp);
				compute(result,exp+"-"+curStr, nextStr, target, cur_num-curTmp, -curTmp);
				compute(result,exp+"*"+curStr, nextStr, target, (cur_num - pre_num) + pre_num*curTmp, pre_num*curTmp);
			}
			else{
				compute(result, curStr, nextStr, target, curTmp, curTmp);
			}
		}
	}
	vector<string> addOperators(string num, int target) {
		vector<string> result;
		string exp = "";
		long cur_num = 0;
		long pre_num = 0;
		compute(result, exp, num, target, cur_num, pre_num);
		return result;
	}
};

参考:https://segmentfault.com/a/1190000003797204

282. Expression Add Operators

标签:

原文地址:http://blog.csdn.net/janestar/article/details/52154617

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!