12345這五個數,列印出它所有的組合。4不能在中間,3和5不能挨著

iteye_9089發表於2020-04-07
public class TestIntNumber {

private int[] numbers = new int[] { 1, 2, 3, 4, 5 };

public int n;

private String lastResult = "";

private boolean validate(String s) {
if (s.compareTo(lastResult) <= 0)
return false;
if (s.charAt(2) == '4')
return false;
if (s.indexOf("35") >= 0 || s.indexOf("53") >= 0)
return false;
return true;
}

public void list(String index, String result) {
for (int i = 0; i < numbers.length; i++) {
if (index.indexOf(i + 48) < 0) {
String s = result + String.valueOf(numbers[i]);
if (s.length() == numbers.length) {
if (validate(s)) {
System.out.println(s);
lastResult = s;
n++;
}
break;
}
list(index + String.valueOf(i), s);
}
}
}

public static void main(String[] args) {
TestIntNumber t = new TestIntNumber();
t.list("", "");
System.out.println("總數:" + t.n);

}

}

相關文章