"Leetcode" Perfect Squares

Source: Internet
Author: User

Title Link: https://leetcode.com/problems/perfect-squares/

Topic:

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, return3Because12 = 4 + 4 + 4; given n =13, return2Because13 = 4 + 9.

Ideas:

N=m^2+s
m= (int) math.sqrt (n) takes the entire table down to the maximum possible total number of squares c[i] represents the recursive formula for the minimum number of complete squares that comprise I:

C[i] =1+c[s] Consider 12=3^2+3 c[12]=1+c[3]=1+3=4, but 12=4+4+4 is c[12]=3
So not m for the maximum square number will be able to get c[i], need to traverse all j<m n=j^2+k min (1+c[k])

Algorithm:

public int numsquares (int n) {      int c[] = new Int[n + 1];      for (int i = 1; I <= n; i++) {          int tmp = (int) math.sqrt (i);          C[i] = c[i-tmp * TMP] + 1;          for (int j = tmp-1; J >= 1; j--) {              tmp = J * J;              C[i] = Math.min (c[i-tmp] + 1, c[i]);          }      }      return c[n];  }  


"Leetcode" 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.