[Leetcode] Perfect Squares Total Square number

Source: Internet
Author: User

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 .

Credits:
Special thanks to @jianchao. Li.fighter for adding the problem and creating all test cases.

Is super elder brother a person hard update topic, a person hold up leetcode free question of a piece of sky Ah, praise a ~ This problem says is give us a positive integer, ask it can be at least by a few complete square number composition. This problem is to examine the four square sum theorem, to be honest, this is the first time I have heard of this theorem, days, and my math is the language teacher taught it?! Gossip not much, come back to do the problem. First of all, a very efficient method, according to the four square sum theorem, any positive integer can be expressed as the sum of 4 integers, in fact, can be expressed as the sum of the squares of 4 or less, then that is, the return result is only three-way or 4 one of them, first we will be digitized briefly, because a number if the factor 4 , then we can remove the 4, not affect the results, such as 2 and 8,3 and 12 and so on, the return of the same results, the reader can self-lift more chestnuts. Another thing that can be reduced is that if a number is divided by more than 8 7, then it must be made up of 4 complete squares, which is not proof, because I will not prove that the reader can verify it by itself. Then after two steps, a large number is likely to become very small, greatly reducing the computational time, the following we try to split it into two squares of the sum, if the demolition succeeds then will return 1 or 2, because one of the squares may be 0. (Note: Since the input n is a positive integer, there is no case of two squared numbers of 0). Pay attention to the following !! A +!! b This expression, probably a lot of people do not understand the meaning of this, in fact, very simple, exclamation ! For logical inversion, then a positive integer is logically reversed to 0 and then reversed to 1, so use two exclamation marks! The function is to see if A and B are positive integers, both are positive integers return 2, only one is a positive integer return 1, see the code is as follows:

Solution One:

classSolution { Public:    intNumsquares (intN) { while(n%4==0) n/=4; if(n%8==7)return 4;  for(intA =0; A * a <= n; ++a) {intb = sqrt (N-A *a); if(A * a + b * b = =N) {return!! A +!!b; }        }        return 3; }};

This problem is far more than this one solution, we can also use dynamic programming of programming, we create a one-dimensional DP array of length N+1, the first value is initialized to 0, the remaining values are initialized to Int_max, I from 0 loop to n,j from 1 loop to I+j*j <= n position, and then each update dp[i+j*j] value, dynamically update the DP array, where dp[i] means that positive integer I can be less than a number of complete square number, then we ask N, that is, return dp[n], that is, the last number of the DP array, see the code as follows:

Solution Two:

//DPclassSolution { Public:    intNumsquares (intN) {vector<int> dp (n +1, Int_max); dp[0] =0;  for(inti =0; I <= N; ++i) { for(intj =1; i + J * J <= N; ++j) {Dp[i+ J * J] = min (Dp[i + j * j], Dp[i] +1); }        }        returnDp.back (); }};

Here is a DP solution, this solution is somewhat different from the above, the solution is to initialize the entire length of the n+1 of the DP number, but the order of initialization is indeterminate, and this method only initializes the first value of 0, then in the loop to calculate, each time the length of a DP array is added, Inside that for loop at the end of a loop, even if the next number consists of a few complete square numbers, until it is added to the n+1, return, to more intuitively see the difference between the two DP methods, it is recommended to print out the values of the DP numbers after each loop to observe the order of their updates, see the code below:

Solution Three:

//DPclassSolution { Public:    intNumsquares (intN) {vector<int> DP (1,0);  while(Dp.size () <=N) {intm = Dp.size (), val =Int_max;  for(inti =1; I * I <= m; ++i) {val= Min (val, dp[m-i * i] +1);        } dp.push_back (Val); }        returnDp.back (); }};

Finally, we introduce a method of recursive recursion,

[Leetcode] Perfect Squares Total Square number

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.