Leetcode Note: Perfect Squares
I. Description
Given a positive integer n, find the least number of perfect square numbers (for example,1, 4, 9, 16, ...
) Which sumn
.
For example, givenn = 12
, Return 3 because12 = 4 + 4 + 4
; Givenn = 13
, Return 2 because13 = 4 + 9
.
Ii. Question Analysis
The general idea of this question is to give a target integer and calculate the minimum number of the target integer from the total number of integers.
A better solution is to use dynamic planning. We all know the number of channels.x
It can be decomposed into an arbitrary number.a
Add a Worker Numberb * b
, That isx = a + b * b
. Therefore, it can constitute a target integer.x
The minimum number of workers is composeda
Add the minimum number of shards1
.
Iii. Sample Code
class Solution {public: int numSquares(int n) { static vector
sqrtNum(1, 0); if(sqrtNum.size() >= n + 1) return sqrtNum[n]; while(sqrtNum.size() <= n + 1){ int temp = INT_MAX; for(int j = 1; j * j <= sqrtNum.size(); j++) temp = min(temp, sqrtNum[sqrtNum.size() - j * j] + 1); sqrtNum.push_back(temp); } return sqrtNum[n]; }};
Iv. Summary
Another use of dynamic planning. It is worth further learning!