Java回溯法对数字的全排列


原文:https://blog.csdn.net/iloveyougirls/article/details/55044401


一、对于不重复数字的全排列(例如:1,2,3,4,5,7,8,9)

1.用数学的方法来算很简单,排列的结果是9!种情况;

下面是简单的一个代码的例子:
[java]  view plain  copy
  1. public class Main {  
  2.     static int count = 0;  
  3.     public static void main(String[] args) {  
  4.         int[] a = {1,2,3};  
  5.         test(a,0);  
  6.         System.out.println(count);  
  7.     }  
  8.     public static void test(int[] a,int b){  
  9.         if(b>=a.length){  
  10.             count++;  
  11.             System.out.println(java.util.Arrays.toString(a));  
  12.         }  
  13.         for (int i = b; i < a.length; i++) {  
  14.             {int k = a[b];a[b] = a[i];a[i] = k;}//两个数字,进行交换  
  15.             test(a,b+1);//用递归进行下一个数的交换  
  16.             {int k = a[b];a[b] = a[i];a[i] = k;}//再次交换两个数字,换回来  
  17.         }  
  18.     }  
  19. }  

输出结果:

[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 2, 1]
[3, 1, 2]
6

二、有些时候,有重复的数字进行排列组合(例如:1,2,2)

这样的数字比较少的,很简单一眼就能看得出有3种情况的排列;

把上面的代码稍做判断就可以的到重复数字的全排列:

[java]  view plain  copy
  1. public class Main {  
  2.     static int count = 0;  
  3.     public static void main(String[] args) {  
  4.         int[] a = {1,2,2};  
  5.         test(a,0);  
  6.         System.out.println(count);  
  7.     }  
  8.     public static void test(int[] a,int b){  
  9.         if(b>=a.length){  
  10.             count++;  
  11.             System.out.println(java.util.Arrays.toString(a));  
  12.         }  
  13.         for (int i = b; i < a.length; i++) {  
  14.             if(!is(a,b,i)) continue;   
  15.             {int k = a[b];  
  16.             a[b] = a[i];  
  17.             a[i] = k;}  
  18.             test(a,b+1);  
  19.             {int k = a[b];  
  20.             a[b] = a[i];  
  21.             a[i] = k;}  
  22.         }  
  23.     }  
  24.     /*排除重复情况的组合*/  
  25.     public static boolean is(int[] a,int b,int i){  
  26.         for (int j = b; j < i; j++) {  
  27.             if(a[i]==a[j]){  
  28.                 return false;  
  29.             }  
  30.         }  
  31.         return true;  
  32.     }  
  33. }  

输出结果:

[1, 2, 2]
[2, 1, 2]
[2, 2, 1]
3



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值