class Solution {
public int[] countBits(int n) {
int[] result=new int[n+1];
for(int i=0;i<=n;++i){
result[i]=oneCount(i);
}
return result;
}
public int oneCount(int x){
int count=0;
while(x!=0){
x=x&(x-1);
++count;
}
return count;
}
}
动态规划:
class Solution {
public int[] countBits(int n) {
int[] result=new int[n+1];
for(int i=1;i<=n;++i){
result[i]=result[i&(i-1)]+1;
}
return result;
}
}
本文介绍了一种使用动态规划优化的二进制计数算法,对比了传统方法与动态规划版本的效率提升。通过`countBits`函数,利用位操作减少重复计算,显著简化了求解过程。
752

被折叠的 条评论
为什么被折叠?



