【问题标题】:Permutation of integers from an array given lengh给定长度的数组中整数的排列
【发布时间】:2013-11-15 15:49:18
【问题描述】:

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

问题是:给定一个范围为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);
}

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

【问题讨论】:

  • count的声明在哪里?

标签: algorithm recursion permutation


【解决方案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.

【讨论】:

  • 但我不明白为什么最后要反向交换?
  • @JudyJiang 因为,如果你不这样做,你会在递归时弄乱元素的顺序。并且当您运行 for 循环时,您希望获取所有不同的元素(否则您会重复值),但是,由于顺序发生了变化(并且不会变回),这不再得到保证。 (你可以检查取出它时会发生什么 - 它不断重复0,1,2,X0,1,9,X,而不是0,1,3,X0,1,4,X等)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-14
  • 1970-01-01
  • 2019-07-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多