zoukankan      html  css  js  c++  java
  • 869. 重新排序得到 2 的幂

    回溯

        static Set<Integer> set=new HashSet<>();
        static{
            for(int i=1;i<=(int)1e9;i*=2) set.add(i);
        }
        private int[] cnt=new int[10];
        private int len;
        private boolean dfs(int cur,int pos){
            if(pos==len) return set.contains(cur);
            for(int i=0;i<10;++i){
                if(cnt[i]>0){
                    cnt[i]--;
                    if((cur!=0||i!=0)&&dfs(cur*10+i,pos+1)) return true;
                    cnt[i]++;
                }
            }
            return false;
        }
        public boolean reorderedPowerOf2(int n) {
            while(n!=0){
                cnt[n%10]++;
                n/=10;
                len++;
            }
            return dfs(0,0);
        }
    

    统计数字频次

    预先计算出每个2的幂的各个数字的频次。给定n,若存在某个2的幂的频次分布和n相同则返回true。

        static Map<Integer,int[]> map=new HashMap<>();
        static{
            for(int i=1;i<=(int)1e9;i*=2) {
                int[] cnt=new int[10];
                int n=i;
                while(n!=0){
                    cnt[n%10]++;
                    n/=10;
                }
                map.put(i,cnt);
            }
        }
        public boolean reorderedPowerOf2(int n) {
            int[] cnt=new int[10];
            while(n!=0){
                cnt[n%10]++;
                n/=10;
            }
            for(Integer num:map.keySet()){
                if(Arrays.equals(cnt,map.get(num))) return true;
            }
            return false;
        }
    

    总结

    这道题预处理步骤是提升效率的关键。

  • 相关阅读:
    Java.io.outputstream.PrintStream:打印流
    Codeforces 732F. Tourist Reform (Tarjan缩点)
    退役了
    POJ 3281 Dining (最大流)
    Light oj 1233
    Light oj 1125
    HDU 5521 Meeting (最短路)
    Light oj 1095
    Light oj 1044
    HDU 3549 Flow Problem (dinic模版 && isap模版)
  • 原文地址:https://www.cnblogs.com/Frank-Hong/p/15475129.html
Copyright © 2011-2022 走看看