排列算法的java实践

遇到一个面试题:

用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);  
    }  
}  

说明:上述源码参考了文献1的代码,添加了valid函数。


补充说明:另外一个朋友说可以用trie树,我没试过,留作以后。


参考文章:

1、http://blog.csdn.net/randyjiawenjie/article/details/6313729

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值