具体题目是:122345这6个数,打印出它所有可能的组合;要求4不能在第3位,3和5不能相连。
有好多种方法,现在提供一种,看不明白,求详细讲解,谢谢!
package org.qh.demo;
import java.util.ArrayList;
import java.util.List;
public class demo5 {
public static void main(String[] args) {
int len = 6;
int[] numArray = { 1, 2, 2, 3, 4, 5 };
int[] currentArray = new int[len];
getNextNumber(0, 1, numArray, currentArray);
}
private static void getNextNumber(int preNum, int level, int[] numArray,
int[] currentArray) {
List<Integer> intList = new ArrayList<Integer>();
for (int i = 0; i < numArray.length; i++) {
int currentNum = numArray[i];
if (intList.indexOf(Integer.valueOf(currentNum)) > -1)
continue;
intList.add(currentNum);
// 4不能在第3位出现
if (level == 3 && currentNum == 4)
continue;
if (level != 1) {
// 3和5不能相连
if ((currentNum == 5 && preNum == 3)
|| (currentNum == 3 && preNum == 5)) {
continue;
}
}
currentArray[level - 1] = currentNum;
int nextLevel = level + 1;
if (level == currentArray.length) {
OutArray(currentArray);
return;
} else {
getNextNumber(currentNum, nextLevel,
createNewArray(numArray, i), currentArray);
}
}
}
private static int[] createNewArray(int[] oldArray, int orderNumber) {
if (oldArray.length <= 1)
return null;
int newLen = oldArray.length - 1;
int[] newArray = new int[newLen];
int newOrderNumber = 0;
for (int i = 0; i < oldArray.length; i++) {
if (i == orderNumber)
continue;
newArray[newOrderNumber] = oldArray[i];
newOrderNumber++;
}
return newArray;
}
private static void OutArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
}
System.out.println("");
}
}
|
|