算法——全排列

看这个算式:
☆☆☆ + ☆☆☆ = ☆☆☆
如果每个五角星代表 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 ;
        }
        
    }
}

 

posted @ 2017-04-06 17:44  行动派  阅读(204)  评论(0编辑  收藏  举报