输出1,2,2,3,4,5的所有排列组合,4不能在第三位,3和5不能相邻

 

一个比较优化的算法

  1. import java.util.Set;   
  2. import java.util.TreeSet   
  3. /**  
  4.  * 原始版本没有考虑重复问题,我进行了修正.<br>  
  5.  * 此算法的精华就是,让一个字符串的所有位置都进行互换,<br>  
  6.  * 这样就产生了所有可能出现的字符串。  
  7.  *   
  8.  * @author 赵学庆,nicky_zs <A href="http://www.java2000.net">www.java2000.net</A>  
  9.  */  
  10. public class MyTest {   
  11.   public static void main(String args[]) {   
  12.     char[] number = new char[] { '1''2''2''3''4''5' };   
  13.     perm(number, 0, number.length - 1);   
  14.     System.out.println(set.size());   
  15.     int cols = 10;   
  16.     for (String s : set) {   
  17.       System.out.print(s + " ");   
  18.       if (cols-- == 1) {   
  19.         System.out.println();   
  20.         cols = 10;   
  21.       }   
  22.     }   
  23.   }   
  24.   public static void addNumber(String str) {   
  25.     set.add(str);   
  26.   }   
  27.   public static Set<String> set = new TreeSet<String>();   
  28.   public static void perm(char[] n, int beg, int end) {   
  29.     if (beg == end) {   
  30.       String result = String.valueOf(n);   
  31.       if (n[2] == '4')   
  32.         return;   
  33.       if (result.contains("35") || result.contains("53"))   
  34.         return;   
  35.       addNumber(String.valueOf(n));   
  36.       return;   
  37.     }   
  38.     for (int i = beg; i <= end; ++i) {   
  39.       swap(n, beg, i);   
  40.       perm(n, beg + 1, end);   
  41.       swap(n, beg, i);   
  42.     }   
  43.   }   
  44.   public static int number = 0;   
  45.   public static void swap(char[] n, int a, int b) {   
  46.     char temp = n[a];   
  47.     n[a] = n[b];   
  48.     n[b] = temp;   
  49.   }   
  50. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值