【发布时间】: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