282. 给表达式添加运算符(困难)
题目描述:
给定一个仅包含数字 0-9 的字符串 num 和一个目标值整数 target ,在 num 的数字之间添加 二元 运算符(不是一元)+、- 或 * ,返回 所有 能够得到 target 的表达式。
注意,返回表达式中的操作数 不应该 包含前导零。
考察重点:针对此类返回所有情况的问题,直接使用DFS解决。
public List<String> addOperators(String num, int target) {List<String> res = new ArrayList<>();if (num == null || num.length() == 0) {return res;}help(num, target, 0, 0, 0, "", res);return res;}private void help(String num, int target, long curRes, long diff, int start, String curExp, List<String> expressions) {if (start == num.length() && (long)target == curRes) {expressions.add(new String(curExp));}for (int i = start; i < num.length(); i++) {String cur = num.substring(start, i + 1);if (cur.length() > 1 && cur.charAt(0) == '0') { //按照题目要求,得到的操作数不应该包含前导0,即'0'只能以数字0加入表达式break;}if (curExp.length() > 0) {help(num, target, curRes + Long.valueOf(cur), Long.valueOf(cur), i + 1, curExp + "+" + cur, expressions);help(num, target, curRes - Long.valueOf(cur), -Long.valueOf(cur), i + 1, curExp + "-" + cur, expressions);help(num, target, (curRes - diff) + diff * Long.valueOf(cur), diff * Long.valueOf(cur),i + 1, curExp + "*" + cur, expressions);} else {help(num, target, Long.valueOf(cur), Long.valueOf(cur), i + 1, cur, expressions);}}}