问题描述
我需要编写一个算法,它接受一个整数并返回所有可能的加法格式
I need to write an algorithm that takes an integer and returns all possible format of addition
例如
如果我进入:6
它将返回以下字符串:
0+6=6
1+1+1+1+1+1=6
1+1+1+1+2=6
1+1+1+3=6
1+1+4=6
1+5=6
2+1+1+1+1=6
2+1+1+2=6
2+1+3=6
2+4=6
3+1+1+1=6
3+1+2=6
3+3=6
4+1+1=6
4+2=6
5+1=6
6+0=6
这是我的尝试:
import java.util.*;
public class Test
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter an integer? ");
int num = in.nextInt();
System.out.println();
calculate(num);
}
private static void calculate(int n)
{
int[] arInt = new int[n];
for(int i = 0; i <= n; i++)
{
for(int j = 0; j <= n; j++)
{
arInt[j] = i;
}
// ...
}
}
}
推荐答案
我同意 Brad.完成此操作的最佳方法可能是通过递归.事实上,我昨晚正在研究与此相关的事情.我使用递归回溯算法解决了我的问题.查看维基百科页面:回溯
I agree with Brad. The best way to complete this would probably be through recursion. In fact, I was working on something related to this last night. I solved my problem using a recursive backtracking algorithm. Check out the Wikipedia page: Backtracking
现在,我不保证没有更好、更简单的方法来解决这个问题.但是,通过递归回溯,您将找到所有解决方案.
Now, I make no guarantees that there aren't better, less complex ways to solve this. However, with recursive backtracking you will find all the solutions.
但有一点需要注意,即 0.您可以将任意数量的零放入加法/减法中,结果会相同.
One thing to watch out for though, that 0. You can throw any amount of zeros into an addition/subtraction and it will come out the same.
这篇关于采用整数并返回所有可能的加法格式的算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!