zoukankan      html  css  js  c++  java
  • 算法——全排列

    看这个算式:
    ☆☆☆ + ☆☆☆ = ☆☆☆
    如果每个五角星代表 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 ;
            }
            
        }
    }
  • 相关阅读:
    KNN算法
    从malloc中窥探Linux内存分配策略
    ECC校验原理以及在Nand Flash中的应用
    周大福、周六福、周生生等区分
    USB时钟为什么是48MHz
    NFS网络操作系统介绍以及相关应用
    办公技巧
    嵌入式设备中使用短信服务
    Android App测试要点
    Excel中 设置使得每行的颜色不一样
  • 原文地址:https://www.cnblogs.com/littlewriter/p/6674634.html
Copyright © 2011-2022 走看看