算法——全排列

本文探讨了一个独特的数学问题,即使用1到9的不同数字完成加法等式☆☆☆+☆☆☆=☆☆☆,确保每个数字只使用一次,并找出所有可能的组合。文章提供了具体的例子来说明哪些组合是有效的。

看这个算式:
☆☆☆ + ☆☆☆ = ☆☆☆
如果每个五角星代表 1 ~ 9 的不同的数字。
这个算式有多少种可能的正确填写方法?
+ 286 = 459
+ 173 = 468
+ 295 = 468
+ 492 = 675
以上都是正确的填写法!
注意:
+ 222 = 333 是错误的填写法!
因为每个数字必须是不同的!
也就是说:1~9中的所有数字,每个必须出现且仅出现一次!
注意:
不包括数字“0”!
注意:
满足加法交换率的式子算两种不同的答案。
所以答案肯定是个偶数!

public class Main{
    public static int count=0;
    
    public static void main(String[] args) {
    
        int[]A={1,2,3,4,5,6,7,8,9};
        dfs(A,0);
        System.out.println(count);
        
    }
    private static void dfs(int a[],int step) {
        if (step==a.length) {
            check(a);
        }else {
            for (int i = step; i < a.length; i++) {
                swap(a,step,i);
                dfs(a, step+1);
                swap(a,step,i);
            }
        }

    }
    private static void swap(int[] a, int step, int i) {
        int temp=a[i];
        a[i]=a[step];
        a[step]=temp;
        
    }
    private static void check(int[] A) {
        String tempA="";
        for (int i = 0; i < A.length; i++) {
            tempA+=A[i];
            
        }
        int a=Integer.valueOf(tempA.substring(0,3));
        int b=Integer.valueOf(tempA.substring(3,6));
        int c=Integer.valueOf(tempA.substring(6,9));
        if (a+b==c) {
            count++;
            return ;
        }
        
    }
}

 

转载于:https://www.cnblogs.com/littlewriter/p/6674634.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值