I. Title Description
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...
) which sum to n
.
For example, given n = 12
, return 3 because 12 = 4 + 4 + 4
; given n = 13
, return 2 because 13 = 4 + 9
.
Two. Topic analysis
The main idea of this topic is to give a target integer that calculates the minimum number of the target integer by the total sum of squares.
A better solution is to use dynamic planning. We all know that a number x
can be decomposed into an arbitrary number a
plus a square number b * b
, that is x = a + b * b
. Therefore, the smallest number of squares that can form a target integer x
is the a
smallest number of squares plus 1
.
Three. Sample code
classSolution { Public:intNumsquares (intN) {Static vector<int>Sqrtnum (1,0);if(Sqrtnum.size () >= n +1)returnSqrtnum[n]; while(Sqrtnum.size () <= n +1){inttemp = Int_max; for(intj =1; J * J <= Sqrtnum.size (); J + +) temp = min (temp, sqrtnum[sqrtnum.size ()-J * J] +1); Sqrtnum.push_back (temp); }returnSqrtnum[n]; }};
Four. Summary
Another use of dynamic planning. Worthy of further study!
Leetcode notes: Perfect Squares