zoukankan      html  css  js  c++  java
  • May LeetCoding Challenge28 之 DP+位运算

    4种解法

    1.pop count

    public class Solution {
        public int[] countBits(int num) {
            int[] ans = new int[num + 1];
            for (int i = 0; i <= num; ++i)
                ans[i] = popcount(i);
            return ans;
        }
        private int popcount(int x) {
            int count;
            for (count = 0; x != 0; ++count)
              x &= x - 1; //zeroing out the least significant nonzero bit
            return count;
        }
    }

    2.DP + Most Significant Bit

    public class Solution {
        public int[] countBits(int num) {
            int[] ans = new int[num + 1];
            int i = 0, b = 1;
            // [0, b) is calculated
            while (b <= num) {
                // generate [b, 2b) or [b, num) from [0, b)
                while(i < b && i + b <= num){
                    ans[i + b] = ans[i] + 1;
                    ++i;
                }
                i = 0;   // reset i
                b <<= 1; // b = 2b
            }
            return ans;
        }
    }

    3.DP + Least Significant Bit

    public class Solution {
      public int[] countBits(int num) {
          int[] ans = new int[num + 1];
          for (int i = 1; i <= num; ++i)
            ans[i] = ans[i >> 1] + (i & 1); // x / 2 is x >> 1 and x % 2 is x & 1
          return ans;
      }
    }

    4.DP + Last Set Bit

    public class Solution {
      public int[] countBits(int num) {
          int[] ans = new int[num + 1];
          for (int i = 1; i <= num; ++i)
            ans[i] = ans[i & (i - 1)] + 1;
          return ans;
      }
    }
  • 相关阅读:
    17多校6 HDU
    E. Present for Vitalik the Philatelist 反演+容斥
    HDU
    F. Cowmpany Cowmpensation dp+拉格朗日插值
    hdu6088 组合数+反演+拆系数fft
    任意模数fft
    Codeforces Round #258 (Div. 2)E
    bzoj3670: [Noi2014]动物园
    HDU
    IO-InputStreamReader
  • 原文地址:https://www.cnblogs.com/yawenw/p/13033415.html
Copyright © 2011-2022 走看看