【坚持每日一题9.3】282. 给表达式添加运算符

给定一个仅包含数字 0-9 的字符串 num 和一个目标值整数 target ,在 num 的数字之间添加 二元 运算符(不是一元)+、- 或 * ,返回所有能够得到目标值的表达式。

示例 1:

输入: num = “123”, target = 6
输出: [“1+2+3”, “123”]
示例 2:

输入: num = “232”, target = 8
输出: [“23+2", "2+32”]
示例 3:

输入: num = “105”, target = 5
输出: [“1*0+5”,“10-5”]
示例 4:

输入: num = “00”, target = 0
输出: [“0+0”, “0-0”, “0*0”]
示例 5:

输入: num = “3456237490”, target = 9191
输出: []

java代码:
class Solution {

 public ArrayList<String> answer;
 public String digits;
 public long target;

 public void recurse(
     int index, long previousOperand, long currentOperand, long value, ArrayList<String> ops) {
   String nums = this.digits;

   // Done processing all the digits in num
   if (index == nums.length()) {

     // If the final value == target expected AND
     // no operand is left unprocessed
     if (value == this.target && currentOperand == 0) {
       StringBuilder sb = new StringBuilder();
       ops.subList(1, ops.size()).forEach(v -> sb.append(v));
       this.answer.add(sb.toString());
     }
     return;
   }

   // Extending the current operand by one digit
   currentOperand = currentOperand * 10 + Character.getNumericValue(nums.charAt(index));
   String current_val_rep = Long.toString(currentOperand);
   int length = nums.length();

   // To avoid cases where we have 1 + 05 or 1 * 05 since 05 won't be a
   // valid operand. Hence this check
   if (currentOperand > 0) {

     // NO OP recursion
     recurse(index + 1, previousOperand, currentOperand, value, ops);
   }

   // ADDITION
   ops.add("+");
   ops.add(current_val_rep);
   recurse(index + 1, currentOperand, 0, value + currentOperand, ops);
   ops.remove(ops.size() - 1);
   ops.remove(ops.size() - 1);

   if (ops.size() > 0) {

     // SUBTRACTION
     ops.add("-");
     ops.add(current_val_rep);
     recurse(index + 1, -currentOperand, 0, value - currentOperand, ops);
     ops.remove(ops.size() - 1);
     ops.remove(ops.size() - 1);

     // MULTIPLICATION
     ops.add("*");
     ops.add(current_val_rep);
     recurse(
         index + 1,
         currentOperand * previousOperand,
         0,
         value - previousOperand + (currentOperand * previousOperand),
         ops);
     ops.remove(ops.size() - 1);
     ops.remove(ops.size() - 1);
   }
 }

 public List<String> addOperators(String num, int target) {

   if (num.length() == 0) {
     return new ArrayList<String>();
   }

   this.target = target;
   this.digits = num;
   this.answer = new ArrayList<String>();
   this.recurse(0, 0, 0, 0, new ArrayList<String>());
   return this.answer;
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值