题目1、用1、2、2、3、4、5这六个数,打印出所有不同的排列
public class test {
static int count = 0;//排列种类
public static void main(String[] args) {
// TODO Auto-generated method stub
String s = "122345";
pailie(s, "");
System.out.println(count);
}
private static void pailie(String s, String p) {
// TODO Auto-generated method stub
//System.out.println("s: "+s);
//System.out.println("p: "+p);
if (s.length() < 1) {
count++;
//System.out.println("count: "+ count);
} else {
int index[] = new int[s.length()];
for (int i = 0; i < s.length(); i++) {// 该循环将所有的字符第一次出现的位置记录在数组index中;
index[i] = s.indexOf(s.charAt(i));
}
for (int i = 0; i < s.length(); i++) {
if (i == index[i]) {
pailie(s.substring(1), p + s.substring(0, 1));
}
//循环移位,使每次都是在起始位置选择第一个
s = s.substring(1) + s.substring(0,1);
}
}
}
}
题目2、用1、2、2、3、4、5这六个数,打印出所有排列,要求:“4”不能排在第三位。“3”与“5”不能相连;
public class test {
static int count = 0;//排列种类
private static String[] mustExistNumber = new String[] { "1", "2", "2", "3", "4", "5" };
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int i = 122345; i <= 543221; i++) {
if (isValidNumber(String.valueOf(i))) {
System.out.println(i);
count ++;
}
}
System.out.println(count);
}
private static boolean isValidNumber(String str) {
// TODO Auto-generated method stub
//检查是否包含12345这5个数字,不包含返回false
for (String number : mustExistNumber) {
if (str.indexOf(number) < 0) {
return false;
}
}
//检查是否有两个2,只有一个返回false
if (str.lastIndexOf("2") == str.indexOf("2")) {
return false;
}
//检查4在不在第3位,是返回false
if (str.charAt(2) == '4') {
return false;
}
//检查是否35在一起
if (str.indexOf("35") >= 0 || str.indexOf("53") >= 0) {
return false;
}
return true;
}
}