【问题标题】:Recursively find combinations of three numbers that sum up to given number递归查找三个数字的组合,总和为给定数字
【发布时间】:2019-05-19 21:05:52
【问题描述】:

给定一个介于 1 到 30 之间的数字,找出总和等于该数字的所有三数组合,并在不使用循环的情况下返回组合的数量。 例如,给定 5,打印

1 + 1 + 3 
1 + 2 + 2 
1 + 3 + 1 
2 + 1 + 2 
2 + 2 + 1 
3 + 1 + 1

这就是我现在所拥有的,使用 Java。

private static int numbers(int num, int num1, int num2, int num3){
    boolean valid_solution = num1+num2+num3 == num;
    int counter = 0;
    if (valid_solution){
      System.out.println(num1+" + "+num2+" + "+num3);
      counter++;
    }
    if (num1>10 || num2>10 || num3>10 || num1+num2+num3>num){
      return counter;
    }
    counter += numbers(num, num1 + 1, num2, num3)+numbers(num, num1, num2 + 1, num3)+numbers(num, num1, num2, num3 + 1);
    return counter;
  }

  public static int solutions(int num){
    if (num < 0 || num > 30) return 0;
    return numbers(num, 1, 1, 1);
  }

我似乎得到了重复,例如 5-

3 + 1 + 1
2 + 2 + 1
2 + 1 + 2
2 + 2 + 1
1 + 3 + 1
1 + 2 + 2
2 + 1 + 2
1 + 2 + 2
1 + 1 + 3

编辑 - 我也不允许使用全局变量。

【问题讨论】:

    标签: java recursion


    【解决方案1】:

    如果您添加一点日志记录,您可以了解为什么会发生重复

    1:1:1
    2:1:1
    3:1:1
    3 + 1 + 1
    4:1:1
    3:2:1
    3:1:2
    2:2:1
    2 + 2 + 1
    3:2:1
    2:3:1
    2:2:2
    2:1:2
    2 + 1 + 2
    3:1:2
    2:2:2
    2:1:3
    1:2:1
    2:2:1
    2 + 2 + 1
    3:2:1
    2:3:1
    2:2:2
    1:3:1
    1 + 3 + 1
    2:3:1
    1:4:1
    1:3:2
    1:2:2
    1 + 2 + 2
    2:2:2
    1:3:2
    1:2:3
    1:1:2
    2:1:2
    2 + 1 + 2
    3:1:2
    2:2:2
    2:1:3
    1:2:2
    1 + 2 + 2
    2:2:2
    1:3:2
    1:2:3
    1:1:3
    1 + 1 + 3
    2:1:3
    1:2:3
    1:1:4
    counter:9
    

    因此,由于您对递增数字进行递归调用,因此当您递归调用 num2+1 时,您需要确保 num1 小于或等于 num2 以避免重复

    【讨论】:

      【解决方案2】:

      我怀疑我的这段代码远不是一个好的解决方案,但谁知道呢,它可能会在某种程度上对你有所帮助。

      public class FindSumCombinations {
      
      static int start = 5;
      static int comb1 = 0;
      static int comb2 = 0;
      
      public static void main(String[] args) {
          comb1(start);
      }
      public static int comb1(int x){
          if(x == 0) return 0;
          comb1 = x;
          comb2(x);
          return comb1(x-1);
      }
      
      public static int comb2(int x){
          if(x == 0) return 0;
          comb2 = x;
          comb3(x);
          return comb2(x-1);
      }
      
      public static int comb3(int x){
          if(x == 0) return 0;
          if(x + comb2 + comb1 == start){
              System.out.println(comb1 + "+" + comb2 + "+" + x);
              System.out.println(x + "+" + comb1 + "+" + comb2);
              System.out.println(comb2 + "+" + x + "+" + comb1);
          }
          return comb3(x-1);
      }
      

      }

      【讨论】:

      • 很遗憾,不能使用静态变量。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-16
      • 2012-11-18
      • 1970-01-01
      • 2018-03-01
      • 1970-01-01
      相关资源
      最近更新 更多