题目:一个组数:122345这6个数,打印出它所有可能的组合;要求4不能在第3位,3和5不能相连
public class ComboTest {
public static void main(String... args) {
int[] inArrays = {1, 2, 2, 3, 4, 5};
int[] outArrays = new int[inArrays.length];
go(inArrays[0], 1, inArrays, outArrays);
}
public static void go(int preNum, int level, int[] inArrays, int[] outArrays) {
List<Integer> inList = new ArrayList<Integer>();
for (int i = 0; i < inArrays.length; i++) {
if (inList.contains(inArrays[i])) continue;
if (level == 4 && inArrays[i] == 3) continue;
if ((preNum == 3 && inArrays[i] == 5)
|| (preNum == 5 && inArrays[i] == 3))
continue;
outArrays[level - 1] = inArrays[i];
inList.add(inArrays[i]);
if (level == outArrays.length) {
System.out.println(Arrays.toString(outArrays));
} else {
go(inArrays[i], level + 1, createNewArray(inArrays, i), outArrays);
}
}
}
private static int[] createNewArray(int[] inArrays, int index) {
int[] newArrays = new int[inArrays.length - 1];
int newIndex = 0;
for (int i = 0; i < inArrays.length; i++) {
if (i == index) continue;
newArrays[newIndex] = inArrays[i];
newIndex++;
}
return newArrays;
}
}