哈哈。一同事说面试题。让我做做。10分钟以内。结果。写完程序+调试花了20分钟。 哎。看来自己老了。其实拿到题目想都没多想就编了。只是现在编码速度太低了。 //用1、2、2、3、4、5这六个数字,打印出所有不同的排列,如:512234、412345等, //要求:"4"不能在第三位,"3"与"5"不能相连,写一个个小程序 import java.util.Map; import javolution.util.FastMap; public class test1 { public static Map<String , Integer> mymap = FastMap.newInstance(); public static int count = 0; public static void main(String[] args) { // 用1、2、2、3、4、5这六个数字,打印出所有不同的排列,如:512234、412345等, //要求:"4"不能在第三位,"3"与"5"不能相连,写一个个小程序 int []a = {0,0,0,0,0,0,0,0}; StringBuffer b = new StringBuffer(); dfs(1, a, b); System.out.println("OK"); } public static void dfs(int l,int []a,StringBuffer b){ if(l > 7) return; if(l == 7 ) { String str=b.toString().replace("6", "2"); if(mymap.containsKey(str)){ return; }else{ count++; System.out.println(count+":"+str); mymap.put(str,1); return; } } for(int i = 1 ;i <= 6 ;i++){ if(l==3 && i == 4){ continue; } if(l> 1 && i == 3 && b.lastIndexOf("5") == l-2){ continue; } if(l>1 && i == 5 && b.lastIndexOf("3") == l-2){ continue; } if(a[i] == 0){ a[i] = 1; b.append(i); dfs(l+1, a, b); b = b.deleteCharAt(l-1); a[i] =0; } } } }

评论