标签:
dfs, 思路就是对于加减法直接操作,但是对于乘法,要保留做乘法之前的值
比如 输入是1322
假设已经到了1 + 3,我们想尝试1 + 3 * 2,这时如果直接用2 * 4则会出错,所以我们与4同时传入的参数还应该有上一步操作之前的值,即为1. 当我们采用乘法时,应该用(4 - 1) * 2 + 1作为下一个传入的值,同时1依然为上一步操作的值。。。。说了半天其实我也不知道自己在说什么。。。上代码吧
public class Solution { private List<String> result = new ArrayList<String>(); public List<String> addOperators(String num, int target) { helper(num, target, 0, 0, ""); return result; } public void helper(String num, int target, long val, long pre, String str) { if (val == target && num.length() == 0) { result.add(str); return; } int length = num.length(); for (int i = 1; i <= length; i++) { if (i > 1 && num.charAt(0) ==‘0‘) { return; } long left = Long.valueOf(num.substring(0, i)); String next = num.substring(i); if (str.length() == 0) { helper(next, target, left, 0, String.valueOf(left)); } else { //+ helper(next, target, val + left, val, str + "+" + String.valueOf(left)); //- helper(next, target, val - left, val, str + "-" + String.valueOf(left)); //* helper(next, target, pre + (val - pre) * left, pre, str + "*" + String.valueOf(left)); } } } }
标签:
原文地址:http://www.cnblogs.com/vision-love-programming/p/4996547.html