思路:动态规划
先找规律:每逢数字是2的次方,均为1
递推方程:dp[i]=dp[i-k]+dp[k];其中k是小于i的最近一个2的整数次方
class Solution { public: vector<int> countBits(int num) { vector<int> res; int k=2; if(num<0) return res; res.push_back(0);if(num==0) return res; res.push_back(1);if(num==1) return res; for(int i=2;i<=num;i++){ if(i%k==0){res.push_back(1);k=i;continue;}//开始写错了,写成i%2==0,导致bug //if(i==7)cout<<i-k<<" "<<res[i-k]<<" "<<k<<""<<res[k]; res.push_back(res[i-k]+res[k]); } return res; } };