LeetCode 338. count bits (dynamic programming)

Title Description

Given a non-negative integer num. For 0 ≤ i ≤ i, each digital num range, which calculates the number of binary digits 1 and returns them as an array.

Example 1:

Input: 2
Output: [0,1,1]
Example 2:

Input: 5
Output: [0,1,1,2,1,2]

Thinking

Here Insert Picture Description
See link

Code

class Solution:
	def countBits(self,num:int):
		dp = [0]*(num+1)
		for i in range(1,num+1):
			if(i%2 == 1):
				dp[i] = dp[i-1] + 1
			else:
				dp[i] = dp[i//2]
		return dp
test = Solution()
test.countBits(5)	

effect

Here Insert Picture Description

Published 80 original articles · won praise 239 · Views 7092

Guess you like

Origin blog.csdn.net/weixin_37763870/article/details/104174840