Leetcode notes: Perfect Squares

Source: Internet
Author: User

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

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.