LeeCode338比特位计数(Java)(动态规划)

题目链接:LeeCode338比特位计数
题目描述:在这里插入图片描述
根据二进制数的性质,1,2,4,8…都只有一个1后面的可能是往上加或者加这些是1的数,取小值就行

public int[] countBits(int num) {
    
    
        if(num==0)return new int[]{
    
    0};
        if(num==1)return new int[]{
    
    0,1};
        int n=1;
        int[] dp=new int[num+1];
        dp[0]=0;
        dp[1]=1;
        for (int i = 2; i <= num; i++) {
    
    
            if(n*2==i){
    
    
                dp[i]=1;
                n*=2;
                continue;
            }else {
    
    
                dp[i]=Math.min(dp[n]+dp[i-n],dp[i-1]+1);
            }
        }
        return dp;
    }

猜你喜欢

转载自blog.csdn.net/weixin_43590593/article/details/113703310