// 排列组合
public class Main {
static Stack<Integer> stack = new Stack<>();
public static void main(String[] args) {
int shu[] = {1,2,3,4};
f(shu,4,0);
}
/**
* @param shu 待选择的数组
* @param targ 要选择多少个次
* @param cur 当前选择的是第几次
*/
private static void f(int[] shu, int targ, int cur) {
if (targ==cur){
System.out.println(stack);
return;
}
for (int i = 0; i < shu.length; i++) {
if (!stack.contains(shu[i])){
stack.add(shu[i]);
f(shu,targ,cur+1);
stack.pop();
}
}
}
}
结果:
[1, 2, 3, 4]
[1, 2, 4, 3]
[1, 3, 2, 4]
[1, 3, 4, 2]
[1, 4, 2, 3]
[1, 4, 3, 2]
[2, 1, 3, 4]
[2, 1, 4, 3]
[2, 3, 1, 4]
[2, 3, 4, 1]
[2, 4, 1, 3]
[2, 4, 3, 1]
[3, 1, 2, 4]
[3, 1, 4, 2]
[3, 2, 1, 4]
[3, 2, 4, 1]
[3, 4, 1, 2]
[3, 4, 2, 1]
[4, 1, 2, 3]
[4, 1, 3, 2]
[4, 2, 1, 3]
[4, 2, 3, 1]
[4, 3, 1, 2]
[4, 3, 2, 1]
分析过程:
原文:https://www.cnblogs.com/fdy-study-consist/p/13821068.html