題目描述
Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.
Example:
For num = 5
you should return [0,1,1,2,1,2]
.
解題思路
一般的思路,爲每一個數求出二進制,是‘1’則對應的計數器加一。但是我估計應該會超時。由於剛學過動態規劃,我就想能不能往那邊靠。動態規劃的思想就是,把大問題變成小問題,而這個小問題你在前面已經解決而且被記錄下了結果(一般是一個數組)。加上,一說到二進制,自然會想到不斷地模2。於是,開始找規律,找到大數和小數二進制的關係。(關係如下圖)
代碼如下
class Solution {
public:
vector<int> countBits(int num) {
if (num == 0)
return vector<int>(1, 0);
vector<int> re(num+1, 0);
re[1] = 1;
for (int i = 1; i <= num; i++) {
int tmp = i;
int count = 0;
while (re[tmp] == 0) {
if (tmp == 0)
break;
tmp % 2 == 0 ? count + 0 : count++;
tmp /= 2;
}
re[i] = re[tmp] + count;
}
return re;
}
};