[英]Number of ways to calculate the sum of 3 objectives
对于给定的num=4
和变量a
, b
, c
,它们的值可以从1 to 10
。 我想计算可以添加这 3 个变量以获得值num
的方法的数量。 例如,对于num=4
1+1+2, 2+1+1, 1+2+1
有3种方法
我正在尝试使用递归。 也许我在这里遗漏了一些重要的东西,我会接受你的建议!
// we can assume the values are positive
// we can assume the num is geater than 4
public static int numbers(int a, int b, int c, int num) {
Integer counter = 0;
if (a + b + c > num) {
return 0;
}
// if we reached a variation of num we add to counter
if (a + b + c == num) {
return counter++;
}
// if we didnt reach a variation of 0
// we do recurion to a+1 then recurion where we add to b and c
if (a + b + c < num && a < num - 1 && b < num - 1 && c < num - 1) {
return numbers(a++, b, c, num) + numbers(a, b++, c, num);
}
// we add to c if its not equal to a so we dont get double
if (a + b + c < num && a < c) {
return numbers(a, b, c++, num);
}
return counter;
}
您的方法存在一些问题,即:
return counter++;
实际上应该是return 1;
您不能增加变量(例如a++
),否则在递归调用期间您将不会通过所有可能的路径 go 。 这里:
return numbers(a++, b, c, num) + numbers(a, b++, c, num);
您只有两条路径,但实际上有 3 条,即:
return numbers(a + 1, b, c, num) +
numbers(a, b + 1, c, num) +
numbers(a, b, c + 1, num);
然而,现在算法的问题是它会有重复的递归路径。 因此,您调整该方法以避免这种情况:
public static void numbers(int a, int b, int c, int num, Set<String> combinations){
if (a + b + c <= num) {
if (a + b + c == num) {
combinations.add("(" + a + "," + b + "," + c + ")");
} else {
numbers(a + 1, b, c, num, combinations);
numbers(a, b + 1, c, num, combinations);
numbers(a, b, c + 1, num, combinations);
}
}
}
使用集合来避免重复。
一个运行的例子:
public class Main {
public static void numbers(int a, int b, int c, int num, Set<String> combinations){
if (a + b + c <= num) {
if (a + b + c == num) {
combinations.add("(" + a + "," + b + "," + c + ")");
} else {
numbers(a + 1, b, c, num, combinations);
numbers(a, b + 1, c, num, combinations);
numbers(a, b, c + 1, num, combinations);
}
}
}
public static void main(String[] args)
{
Set<String> combinations = new LinkedHashSet<>();
numbers(1, 1, 1, 5, combinations);
combinations.forEach(System.out::println);
System.out.println("Count : "+combinations.size());
}
}
对于输入:
numbers(1, 1, 1, 5, combinations);
你会得到 output:
(3,1,1)
(2,2,1)
(2,1,2)
(1,3,1)
(1,2,2)
(1,1,3)
Count : 6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.