遇到一个面试题:
用1、2、3、4、5这5个数字,用java写一个程序,打印出所有不同的排列 要求:"4"不能在第三位,"3"与"5"不能相连。
这里用到了排列算法。
解题思路:
1、计算出这5个数字的全部排列,即Permutation。
2、根据条件,排除不满足条件的。
3、打印出符合要求的,并计算总数。
java源码实践如下:
public class Permutation { public static int total = 0; public static void swap(String[] str, int i, int j) { String temp = new String(); temp = str[i]; str[i] = str[j]; str[j] = temp; } public static void arrange (String[] str, int st, int len) { String result = ""; if (st == len - 1) { for (int i = 0; i < len; i ++) { result += str[i]; } if (valid(result)) { System.out.println(result); total++; } } else { for (int i = st; i < len; i ++) { swap(str, st, i); arrange(str, st + 1, len); swap(str, st, i); } } } public static boolean valid(String str) { if (str.charAt(2) == '4' || str.indexOf("35") >= 0 || str.indexOf("53") >= 0) { return false; } else { return true; } } public static void main(String[] args) { String[] str = {"1", "2", "3", "4", "5"}; arrange(str, 0, str.length); System.out.println("the total permutation is " + total); } }
补充说明:另外一个朋友说可以用trie树,我没试过,留作以后。
参考文章:
1、http://blog.csdn.net/randyjiawenjie/article/details/6313729