338. Counting Bits
原题:
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].
Follow up:
It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
Space complexity should be O(n).
Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
解析:统计每个数字对应2进制中含有1的个数,显然是要用动态规划,首先分成奇数和偶数分别处理,奇数直接是前一个偶数+1,而偶数÷2就是当前1的个数,因为偶数最后位必定是1
具体代码如下:
class Solution {
public:
vector<int> countBits(int num) {
vector<int> v(num + 1);
v[0] = 0;
for(int i = 1;i <= num;i++){
if(i % 2 == 1)v[i] = v[i-1] + 1;
else v[i] = v[i/2];
}
return v;
}
};
357. Count Numbers with Unique Digits
原题:
Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n.
Example:
Given n = 2, return 91. (The answer should be the total numbers in the range of 0 ≤ x < 100, excluding [11,22,33,44,55,66,77,88,99])
解析:统计从0到n的数中,不含有重复数字的数的个数。所以用动态规划来解的话,对每个数,有两种情况,1、最后一位与前面的某个数字有重复。2、除了最后一位前面的数字已经有重复了。因此创建一个bool数组,用于判断对应数是否有重复数字,首先看有没有重复,若没有,则一个个求余看与最后一位是否相同。
具体代码如下:
class Solution {
public:
int countNumbersWithUniqueDigits(int n) {
int m = pow(10,n);
int sum = 0,i;
vector<bool> v(m);
for(i = 0;i < m;i ++){
int last = i % 10,leave = i / 10;
bool is = true;
while(leave){
if(leave % 10 == last || v[leave] == false){
is = false;
v[i] = false;
break;
}
leave = leave / 10;
}
if(is){
sum++;
v[i] = true;
}
}
return sum;
}
};