条件排列

来源:互联网 发布:数据库连不上的原因 编辑:程序博客网 时间:2024/05/08 21:40
原题如下:用1、2、2、3、4、5这六个数字,用java写一个程序,打印出所有不同的排列,如:512234、412345等,要求:"4"不能在第三位,"3"与"5"不能相连。
全排列
public static void Permutation(char[] chs,int i){
if(chs == null || chs.length <=0){
System.out.println("输入有误");
}
if(i == chs.length){
System.out.println(chs);
}else{
char temp;
for(int j=i; j< chs.length; j++){
if(i != j && chs[i] == chs[j]) continue;  // 不同位置的相同字符不作交换
temp = chs[i];
chs[i] = chs[j];
chs[j] = temp;
Permutation(chs,i+1);
temp = chs[i];
chs[i] = chs[j];
chs[j] = temp;
}
}
}


public static void Permutation(char[] chs,int i){
if(chs == null || chs.length <=0){
System.out.println("输入有误");
}
if(i == chs.length){
if(isCondition(String.valueOf(chs))){
System.out.println(chs);
}
}else{
char temp;
for(int j=i; j< chs.length; j++){
if(i != j && chs[i] == chs[j]) continue;  // 不同位置的相同字符不作交换
temp = chs[i];
chs[i] = chs[j];
chs[j] = temp;
Permutation(chs,i+1);
temp = chs[i];
chs[i] = chs[j];
chs[j] = temp;
}
}
}
private static boolean isCondition(String data){ // 判断是否符合条件
if(data.contains("35") ||data.contains("53")){
return false;
}
if(data.charAt(2)== '4'){
return false;
}
return true;
}
原创粉丝点击