题目
Given a positive integer n, find the least number of perfect square numbers (for example,
1, 4, 9, 16, ...
) which sum to n.
Example1
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.
Example2
Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.
分析
这道题目的意思是给定一个正整数,要求我们找到最少的平方数,它们的和等于这个正整数。
解法一
一开始我尝试从这个正整数减去它最大的平方数入手,判断剩下的数能由多少个平方数组成。但这样做的问题是很可能找不到最少的平方数数目,因为剩下那部分数可能只能由1组成,比如12按这种做法得到的结果就是4。
对于这种问题,最好的方法是分解问题成为一个个易求解的子问题,再分别求解。
我分解问题的方法其实也是在前面的想法上进行改进得到