图解全排列问题_一道笔试题(122345求有条件全排列)的两种做法
packagecom.heyang.p122345;importjava.util.HashSet;importjava.util.Set;/***?用1、2、2、3、4、5這六個數字,用java寫一個程序,打印出所有不同的排列,如:512234、412345等,
*?要求:"4"不能在第三位,"3"與"5"不能相連。
*?說明:?以下為全排列做法
*?作者:heyang(heyang78@gmail.com)
*?創建時間:2010-6-22?上午12:46:37
*?修改時間:2010-6-22?上午12:46:37*/publicclassPermutation{//用于序號privatestaticintindex=1;//用于清除重復的數,因為有兩個2的影響privatestaticSetset=newHashSet();publicstaticvoidmain(String[]?args){
Integer[]?arr02={1,2,2,3,4,5};//Integer[]?arr02={1,2,2};permutation(arr02,0,arr02.length);
}/***?排列函數
*
*?說明:
*@paramarr
*@paramstart
*@paramend
*?創建時間:2010-6-22?上午02:05:12
*?修改時間:2010-6-22?上午02:05:12*/publicstaticvoidpermutation(Integer[]?arr,intstart,intend){if(start
permutation(arr,start+1,end);for(inti=start+1;i
Integer?temp;
temp=arr[start];
arr[start]=arr[i];
arr[i]=temp;
permutation(arr,start+1,end);
temp=arr[i];
arr[i]=arr[start];
arr[start]=temp;
}
}else{
print(arr);
}
}/***?打印函數
*
*?說明:
*@paramarr
*?創建時間:2010-6-22?上午02:05:27
*?修改時間:2010-6-22?上午02:05:27*/privatestaticvoidprint(Integer[]?arr){//"4"不能在第三位if(arr[2]==4){return;
}
StringBuilder?sb=newStringBuilder();for(inti=0;i
sb.append(arr[i]);
}
String?word=sb.toString();//"3"與"5"不能相連if(word.contains("35")||word.contains("53")){return;
}//打印if(set.contains(word)==false){
System.out.println((index++)+""+word);
set.add(word);
}
}
}
總結
以上是生活随笔為你收集整理的图解全排列问题_一道笔试题(122345求有条件全排列)的两种做法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: dbcc dbreindex serve
- 下一篇: 华为mstp多生成树配置_【交换机】交换