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是变化的参数
想了很久也没想出来

解决方案 »

  1.   


    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常量值是为了打印最终每个数组的值
      

  2.   

    恩,题目意思看明白了,这种情况还真得用递归,代码如下,其实跟4L的差不多吧public class RecurTest {
    /**
     * 数组长度
     */
    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万多组解