問題描述
我需要編寫一個(gè)算法,它接受一個(gè)整數(shù)并返回所有可能的加法格式
I need to write an algorithm that takes an integer and returns all possible format of addition
例如
如果我進(jìn)入: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.完成此操作的最佳方法可能是通過遞歸.事實(shí)上,我昨晚正在研究與此相關(guān)的事情.我使用遞歸回溯算法解決了我的問題.查看維基百科頁面:回溯
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
現(xiàn)在,我不保證沒有更好、更簡(jiǎn)單的方法來解決這個(gè)問題.但是,通過遞歸回溯,您將找到所有解決方案.
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.
但有一點(diǎn)需要注意,即 0.您可以將任意數(shù)量的零放入加法/減法中,結(jié)果會(huì)相同.
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.
這篇關(guān)于采用整數(shù)并返回所有可能的加法格式的算法的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!