int a[]={1,2,3,4}//长度为y的数组
for(int i1=0;i1<4;i1++){
for(int i2=0;i2<4;i2++){
for(int i3=0;i3<4;i3++){
.
.//N层循环
.
for(int iN=0;iN<4;iN++){
if(a[i1]+a[i2]+a[i3]+……+a[iN]==20){
System.out.println("相等");
} }
.
.
.
}
}
}java程序能把这个n层嵌套循环改为递归吗?n是变化的参数
想了很久也没想出来
for(int i1=0;i1<4;i1++){
for(int i2=0;i2<4;i2++){
for(int i3=0;i3<4;i3++){
.
.//N层循环
.
for(int iN=0;iN<4;iN++){
if(a[i1]+a[i2]+a[i3]+……+a[iN]==20){
System.out.println("相等");
} }
.
.
.
}
}
}java程序能把这个n层嵌套循环改为递归吗?n是变化的参数
想了很久也没想出来
解决方案 »
- java图片显示
- jar文件运行找不到Main-class
- 关于panel=new JPanel(); JPanel panel=new JPanel();用法
- JAVA和C++各在哪方面较强?
- 有没办法让HashMap的keySet()方法得到的Set顺序与put()入时的一样
- 请高手指点 100分送上 用jcombobox怎么能实现和IE地址栏一样的显示功能
- 98下面如何设置Java的环境变量?
- 关于Jtree:如何根据一个节点的属性值来控制是否让这个节点展开?
- 一次上传两个文件,分别存在不同的目录下,用SmartUpload怎么用
- 一个很菜的问题,解答了马上给分
- 初学java 。无法用面向对象的思维。 而且就不知道程序如何架构起来。谁能帮我改改我的一个hash 查找
- 关于JAVA里面GUI的getText方法可以直接用==比较相等的疑问
public class App { public static boolean finish = false; public static void main(String[] args) {
init(4, 5);
} public static void init(int y, int n) {
int[] a = new int[y];
for (int i = 0; i < y; i++) {
a[i] = i + 1;
}
DoNotKnow(y, n, 0, 0, a);
} public static void DoNotKnow(int y, int n, int current_n, int sum, int[] a) {
if (current_n == n) {
return;
}
int i = 0;
for (i = 0; i < y; i++) {
if (sum + a[i] == 20) {
System.out.println("相等");
System.out.println("a" + current_n + "[" + i + "]=" + a[i]);
finish = true;
return;
}
// System.out.println(current_n);
DoNotKnow(y, n, current_n + 1, sum + a[i], a);
if (finish) {
System.out.println("a" + current_n + "[" + i + "]=" + a[i]);
return;
}
}
}
}
设置finish常量值是为了打印最终每个数组的值
/**
* 数组长度
*/
static final int Y = 4;
/**
* 求和的数字数
*/
static final int N = 10;
/**
* 求和的结果
*/
static final int TARGET = 20;
/**
* 记录搜索的路径
*/
static int[] path = new int[N];
static int solveCount;
static void test(int step, int total) {
if (step == N) {
//如果不要求一定是N个数相加,则把该判断移到外层
if (total == TARGET) {
outputResult();
}
return;
}
for(int i = 1; i <= Y; i++) {
path[step] = i;
test(step + 1, total + i);
}
}
static void outputResult() {
System.out.print("case " + solveCount++ + ":" + path[0]);
for(int i = 1; i < N; i++) {
System.out.print(" + " + path[i]);
}
System.out.println(" = " + TARGET);
}
public static void main(String[] args) {
test(0, 0);
}
}
输出结果:……
case 44792:4 + 4 + 3 + 2 + 1 + 1 + 2 + 1 + 1 + 1 = 20
case 44793:4 + 4 + 3 + 2 + 1 + 2 + 1 + 1 + 1 + 1 = 20
case 44794:4 + 4 + 3 + 2 + 2 + 1 + 1 + 1 + 1 + 1 = 20
case 44795:4 + 4 + 3 + 3 + 1 + 1 + 1 + 1 + 1 + 1 = 20
case 44796:4 + 4 + 4 + 1 + 1 + 1 + 1 + 1 + 1 + 2 = 20
case 44797:4 + 4 + 4 + 1 + 1 + 1 + 1 + 1 + 2 + 1 = 20
case 44798:4 + 4 + 4 + 1 + 1 + 1 + 1 + 2 + 1 + 1 = 20
case 44799:4 + 4 + 4 + 1 + 1 + 1 + 2 + 1 + 1 + 1 = 20
case 44800:4 + 4 + 4 + 1 + 1 + 2 + 1 + 1 + 1 + 1 = 20
case 44801:4 + 4 + 4 + 1 + 2 + 1 + 1 + 1 + 1 + 1 = 20
case 44802:4 + 4 + 4 + 2 + 1 + 1 + 1 + 1 + 1 + 1 = 20有4万多组解