【发布时间】:2019-10-11 01:33:16
【问题描述】:
我需要找到一个使用递归回溯算法的算法,它将所有可能的组合打印到x1+x2+x3 以等于数字。
假设输入数字为 4,因此该方法将打印我 3 个结果:
1 1 2
1 2 1
1 1 2
…… 代码:
public class getResult
public static void results(int n)
{
int[] history= new int[3];
results(n,history,0);
}
private static void results(int n,int[] history,int i)
{
if(n==0)
{
printHistory(history,0,i);
System.out.println();
}
if`(n>0&&i<3)`
{
history[i]=1;
//insert 1 to history in order to go back in case of wrong
// way using backtracking.
results(n-1,history,i+1);//calling the function again, with n-1 , backup history, history[i+1]`
history[i]=2;
results(n-2,history,i+1);
history[i]=3;
results(n-3,history,i+1);
//.....9
}
}
private static void printHistory(int[] history,int from,int to)
{
if(from<to)
{
System.out.print(history[from]+"\t");
printHistory(history,from+1,to);
}
}
}
我有两个问题:
1.如何只打印以x1,x2,x3结尾的结果。
因为现在,如果我尝试输入num=5,它会打印出以下结果:
1 1 3
1 2 2
1 3 1
1 4
2 1 2
2 2 1
2 3
3 1 1
3 2
4 1
5
我想得到只得出 3 个数字的结果(例如没有结果:5、4 1、3 2、2 3)..
2.有没有办法更好地写这些行:
history[i]=1;
results(n-1,history,i+1)`;`
而不是每次复制代码并从数字中手动减去一个数字?(结果应该通过1到9之间的所有数字)
谢谢大家的帮助,如果有不清楚的地方我想帮忙:)
【问题讨论】:
-
要只打印 3 个,您可以在打印结果的位置放置
n == 0 && i == 3而不是n==0 -
@ButiriDan 你是对的!谢谢,那另一个问题呢?
-
我投票决定将此问题作为离题结束,因为它更适合codereview.stackexchange.com,我似乎无法将其选为“迁移...”原因
-
@ButiriDan 但是如果我没有提到,我不允许使用循环。有没有办法用递归调用来编写它?
-
@Jordan_boy 递归调用还在
标签: java arrays algorithm recursion backtracking