我被采访了一个问题,之后我测试了我的代码,发现它错了。 不善于递归。但我无法弄清楚这个问题。给定长度的数组整数排列
问题是:给定一个从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”的声明在哪里? – chill