Generate all combinations of mathematical expressions that add to target (Java homework/interview)

前端 未结 3 874
你的背包
你的背包 2021-01-31 05:39

I\'ve tried to solve the problem below for a coding challenge but could not finish it in 1 hour. I have an idea on how the algorithm works but I\'m not quite sure how to best im

3条回答
  •  南笙
    南笙 (楼主)
    2021-01-31 06:32

    I don't think it's necessary to build a tree, you should be able to calculate as you go -- you just need to delay additions and subtractions slightly in order to be able take the precedence into account correctly:

    static void check(double sum, double previous, String digits, double target, String expr) {
       if (digits.length() == 0) {
         if (sum + previous == target) {
           System.out.println(expr + " = " + target);
         }
       } else {
         for (int i = 1; i <= digits.length(); i++) {
           double current = Double.parseDouble(digits.substring(0, i));
           String remaining = digits.substring(i);
           check(sum + previous, current, remaining, target, expr + " + " + current);
           check(sum, previous * current, remaining, target, expr + " * " + current);
           check(sum, previous / current, remaining, target, expr + " / " + current);
           check(sum + previous, -current, remaining, target, expr + " - " + current);
         }
       }
     }
    
     static void f(String digits, double target) {
       for (int i = 1; i <= digits.length(); i++) {
         String current = digits.substring(0, i);
         check(0, Double.parseDouble(current), digits.substring(i), target, current);
       }
     } 
    

提交回复
热议问题