给定长度的数组的整数排列

时间:2013-11-15 15:49:19

标签: algorithm recursion permutation

我接受了一个问题的采访,之后我测试了我的代码,发现它错了。 不擅长递归。但我无法弄清楚问题所在。

问题是:给定一个0到9的数组范围和一个长度,例如3;生成 给定长度中给定数组的整数排列。 所以,举个例子: 排列应该是:012,013,014,......,345,346 ...... 下面是我的java代码,问题出在哪里? (我认为这是索引或偏移部分) 而且,如果有更好的解决方案!

public void NumPermutation(int[] list, int offset, int[] temp, int index){
    if(index == 4){
       printarray(temp);
    }

    for(int count = offset; count < list.length; count++){
        temp[index++] = list[count];
        int te = list[offset];
        list[offset] = list[count];
        list[count] = te;
        NumPermutation(list, offset, temp, index);
        index -= 1;
    }
}

public void test(int len){
    int[] list = {0,1,2,3,4,5,6,7,8,9};
    int[] temp = new int[4];
    int index = 0, offset = 0;
    NumPermutation(list, offset, temp,index);
}

问题是,每次偏移都会增加 它甚至无法达到最后的数字。

1 个答案:

答案 0 :(得分:1)

你需要:

  • offset+1传递给递归电话。

  • 返回if语句。

  • 在递归调用后反转您的交换。

  • 4替换为temp.length以获得更通用的解决方案。

  • 还最好将index++indexindex -= 1替换为indexindex + 1,而不是。

这导致此代码:(使用标准打印方法替换printarray,假设这是Java)

public static void NumPermutation(int[] list, int offset, int[] temp, int index){
    if(index == temp.length) {
       System.out.println(Arrays.toString(temp));
       return;
    }

    for(int count = offset; count < list.length; count++){
        temp[index] = list[count];

        // swap
        int te = list[offset];
        list[offset] = list[count];
        list[count] = te;

        NumPermutation(list, offset + 1, temp, index + 1);

        // reverse swap
        te = list[offset];
        list[offset] = list[count];
        list[count] = te;
    }
}

Live demo

相关问题