如何在java中构建组合函数?
我正在研究面试问题 而且,我很难理解组合函数 我想构建组合函数 例如,如果输入为如何在java中构建组合函数?,java,arrays,combinations,permutation,Java,Arrays,Combinations,Permutation,我正在研究面试问题 而且,我很难理解组合函数 我想构建组合函数 例如,如果输入为[1,2,3] 然后我必须生成[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1] 但是,它不应该接受长度比输入值短的情况。(例如,[1],[3,2]) 而且,输入中的元素数量可以更改([1,2,3,4],[1,2,3,4,5,6]) 然而,我并不确定如何开始构建这个函数 有人能给出一些想法或例子吗 谢谢正如已经指出的那样,你的意思似乎是,而不是 在我脑海中出现的第一个方法是
[1,2,3]
然后我必须生成[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]
但是,它不应该接受长度比输入值短的情况。(例如,[1]
,[3,2]
)
而且,输入中的元素数量可以更改([1,2,3,4]
,[1,2,3,4,5,6]
)
然而,我并不确定如何开始构建这个函数
有人能给出一些想法或例子吗
谢谢正如已经指出的那样,你的意思似乎是,而不是 在我脑海中出现的第一个方法是递归的——但我不知道它会有多大效率——也许是一个有趣的问题,你的面试问题应该考虑一下。p>
public class Permutations {
// testing
public static void main(String[] args){
permutations(new int[]{1,2,3});
}
public static void permutations(int[] array){
boolean[] chosen = new boolean[array.length];
int[] output = new int[array.length];
permutation_inner(array,chosen,output,0);
}
public static void permutation_inner(int[] array, boolean[] chosen,
int[] output, int depth){
if(depth==array.length){
System.out.println(java.util.Arrays.toString(output));
return;
}
for(int i=0;i<array.length;i++){
if(!chosen[i]){
chosen[i]=true;
output[depth]=array[i];
permutation_inner(array,chosen,output,depth+1);
chosen[i]=false;
}
}
}
}
公共类置换{
//测试
公共静态void main(字符串[]args){
置换(新的int[]{1,2,3});
}
公共静态空置换(int[]数组){
boolean[]selected=新的boolean[array.length];
int[]输出=新的int[array.length];
排列_内部(数组,选择,输出,0);
}
公共静态无效置换_内部(int[]数组,选择布尔[],
int[]输出,int深度){
if(深度==array.length){
System.out.println(java.util.array.toString(output));
返回;
}
对于(int i=0;我不应该是一种排列方法而不是一种组合方法吗?@splungebob我应该说“排列”?我不太确定..但每个案例都应该有相同的长度。它不接受[1],[2,3]…等案例..谢谢selig。它真的帮助我理解面试问题。我将尝试改进功能:)谢谢!!