的所有解决方案我有这样的问题:算法打印方程
假设我们有这个简单的公式
x1 + x2 + x3 + x4 + x5 = 20
,我想打印所有非负整数解这个方程的和我只能使用数字3, 4, 5, 6
例如:
0 + 4 + 4 + 6 + 6 = 20
etc.
我不想写它在特定的编程语言,只在伪代码
任何想法?
的所有解决方案我有这样的问题:算法打印方程
假设我们有这个简单的公式
x1 + x2 + x3 + x4 + x5 = 20
,我想打印所有非负整数解这个方程的和我只能使用数字3, 4, 5, 6
例如:
0 + 4 + 4 + 6 + 6 = 20
etc.
我不想写它在特定的编程语言,只在伪代码
任何想法?
在Java代码中
int []numbers = {0, 3, 4, 5, 6};
int res=20;
int sum=0;
for(int i:numbers)
for(int j:numbers)
for(int k:numbers)
for(int l:numbers)
for(int m:numbers) {
sum = i + j + k + l + m;
if(sum==res) {
String solution = i + " " + j + " " + k + " " + l +" " + m;
Log.i("solution", "---- " + solution);}
}
在伪代码是这样的:
FOR each number1 in the number_list
FOR each number2 in the number_list
FOR each number3 in the number_list
FOR each number4 in the number_list
FOR each number5 in the number_list
sum = number1+number2+number3+number4+number5;
IF sum IS EQUAL TO 20 THEN
Print number1, number2, number3, number4, number5
ENDIF
ENDFOR
ENDFOR
ENDFOR
ENDFOR
ENDFOR
这可能会实现: Finding all possible combinations of numbers to reach a given sum
可以启动组数字为[3,4,5,6],而不是删除一次选择的元素和递归的深度检查,如果你有确切需要的元素数量。
这是更通用的,将允许使用不同数量的元素来解析方程,而无需添加/移除嵌套循环。
我编辑的问题,我只能使用数字3,4 ,5,6 – Johny
然后你不能使用0,所有的解决方案都是非负的。 –
有该方程解的无穷数。你的意思是你想要打印所有非负整数解决方案吗? – JJJ
是的,所有非否定:) – Johny
你想消除重复?例如, '15 + 1 + 2 + 1 + 1'和'15 + 1 + 1 + 2 + 1'将会被取消或保留一个值 – Paul