java中碰到全排列时……

如从1-9这9个数进行运算,每个数只能出现且必须出现一次

例如九个空      _ _ _+_ _ _ =_ _ _满足这样的式子有多少
    static int count = 0;
    public static void ls(int[] a, int start, int end) {  
  
        if (start == end) {  //这个判断用于递归到最后的时候输出相应的字符串

            int x1 = a[0] * 100 + a[1] * 10 + a[2];  
            int x2 = a[3] * 100 + a[4] * 10 + a[5];  
            int x3 = a[6] * 100 + a[7] * 10 + a[8];  
            if (x1 + x2 == x3) {  
                count++;  
               // System.out.println(x1 + "+" + x2 + "=" + x3);  
            }  
            return;  
        }
        else {  
            for (int i = start; i <= end; i++) {  
                int temp = a[i];  
                a[i] = a[start];  
                a[start] = temp;  
                ls(a, start + 1, end);  
                temp = a[i];  
                a[i] = a[start];  
                a[start] = temp;  
            }  
        }  
    }  
再例如 _ _ * _ _ = _ _ * _ _ _
	public static void ls(int[] a, int start, int end) {  
		 
	        if (start == end) {  //这个判断用于递归到最后的时候输出相应的字符串
	            int x1 = a[0] * 10 + a[1];  
	            int x2 = a[2] * 10 + a[3];  
	            int x3 = a[4] * 10 + a[5]; 
	            int x4 = a[6] * 100 + a[7] * 10 + a[8]; 
	            if (x1 * x2 == x3 * x4) {  
	            	//System.out.println(x1 + "*" + x2 + "=" + x3 +"*"+ x4);  
	            	count++;
	            }  
	            return;  
	        }
	       else {  
	            for (int i = start; i <= end; i++) {  
	                int temp = a[i];  // 交换数组第一个元素与后续的元素a[i]与a[start]互换
	                a[i] = a[start];  
	                a[start] = temp; 
	                ls(a, start + 1, end);  // 后续元素递归全排列
	                temp = a[i];  	// 将交换后的数组还原
	                a[i] = a[start];  
	                a[start] = temp;  
	            }  
	        } 
	    }  
public static void main(String[] args) {
		// TODO Auto-generated method stub
		 int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };  
	      ls(a, 0, a.length - 1);  //不能写成allSort(a[], 0, a.length - 1)!!!!
	      System.out.println(count);
	}





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值