Leetcode Perfect Squares

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 = A, return 3 because 12 = 4 + 4 + 4; given n =
Return 2 because 13 = 4 + 9.

Title translation: Give a positive integer n, to ask for at least how many full squares (e.g. 1,4,9,16 ... Added to get N.
For example, given n = 12, return 3, because 12 = 4 + 4 + 4. Given n = 13, return 2, because 13 = 4 + 9.

Specifically, we use an array to record the existing results and initialize them to positive infinity (Int_max). The outer loop variable i from 0 to N,
The inner loop variable J, on the basis of I, plus the total squared of each integer, exceeds N's count. So i + j*j this number takes
The minimum number of full squares is the current value in the array, and the value of the I position plus one, the smaller number between the two.
If the current value is small, it means that we have found the exact number of squares it needs (initially positive infinity). Otherwise, say
On the basis of I plus J squared to meet the conditions, the total number of squares required is the number I need plus one.

Importjava.util.Arrays;classSolution { Public intNumsquares (intN) {int[] DP =New int[n + 1];        Arrays.fill (DP, integer.max_value); dp[0] = 0;  for(inti = 0; I <= N; i++) {             for(intj = 1; i + J * J <= N; J + +) {Dp[i+ J * j] = Math.min (Dp[i + J * j], Dp[i] + 1); }        }        returnDp[n]; }     Public Static voidMain (string[] args) {solution S=Newsolution (); intn = s.numsquares (8);    SYSTEM.OUT.PRINTLN (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.