leetcode 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 1:
1 | Input: 2 |
Example 2:
1 | Input: 5 |
solution one
easy to come up with
1 | dp[0] = 0; |
this is overlap sub problem, and we can come up the DP solution
1 | classs Solution { |
solution two
1 | anthoer function(tricky one): |
Obviously, we can find the pattern for above example, so now we get the general function
dp[index] = dp[index - offset] + 1;
1 | public int[] countBits(int num) { |