问题描述:
Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1’s in the binary representation of i.
计算从0到n每个数的二进制码有多少个1
思路:
这道题我的直觉告诉我用DP,因为后面的结果和前面的结果有联系。事实也是如此,但是我一直在找i与i+1的联系,但其实应该找i与i/2的联系。i与i/2的联系是:如果i的末位是0,则i与i/2含有相同数量的1;如果i的末位是1,那么i比i/2多一个1(就是末尾的那个1)。
代码如下:
class Solution {
public int[] countBits(int n) {
int[] ans=new int[n+1];
for(int i=1; i<=n; i++){
ans[i]=ans[i>>1]+(i&1);
}
return ans;
}
}
时间复杂度:O(n)