279. Perfect Squares 338. Counting Bits

279.Perfect Squares

Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, …) which sum to n.
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.

两个思考方向:
1.向后思考,点i的结果,我们向后更新所有 i + x 2 的值。所以到达i点的时候i的值已经是得到了的;
2.向前思考,对于每个点,我们检查所有 i x 2 的值;
复杂度一样,方法2更直观。

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.
Input: 2
Output: [0,1,1]
Input: 5
Output: [0,1,1,2,1,2]

1.向后思考,对于每个已知的i, i << n 的bits数目必然是与i相同的,那么我们就将所有<=n的这样的数都赋值;如果遇到一个dp[i] == 0很显然这个值没有被更新,也就意味着它不是2的倍数,dp[i] = dp[i-1] + 1;
2.向前思考,对于每个i, 如果是2的倍数,直接取 i >> 1 处的值 ; 反之 dp[i] = dp[i-1]+1;

综合这两道题,发现向前思考的思路其实更贴合dp的思想,用小问题的解来解决大问题。所以以后遇到这类型尽量用向前思考的方式

猜你喜欢

转载自blog.csdn.net/qq_24436311/article/details/81389208