[LeetCode] Perfect Squares

Source: Internet
Author: User

[LeetCode] Perfect Squares

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.

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

Subscribe to see which companies asked this question

Solutions

Dynamic Programming Method. Seasonal Initializationdp[i * i] = 1, The state transition equation isdp[i + j * j] = min(dp[i] + 1, dp[i + j * j]);

Implementation Code

C ++:

// Runtime: 544 msclass Solution {public:    int numSquares(int n) {        vector
  
    dp(n + 1, 0x7fffffff);        for (int i = 0; i * i <= n; i++)        {            dp[i * i] = 1;        }        for (int i = 1; i <= n; i++)        {            for (int j = 1; i + j * j <= n; j++)            {                dp[i + j * j] = min(dp[i] + 1, dp[i + j * j]);            }        }        return dp[n];    }};
  

Java:

// Runtime: 69 mspublic class Solution {    public int numSquares(int n) {        int dp[] = new int[n + 1];        Arrays.fill(dp, Integer.MAX_VALUE);        for (int i = 1; i * i <= n; i++) {            dp[i * i] = 1;        }        for (int i = 1; i <= n; i++) {            for (int j = 1; i + j * j <= n; j++) {                dp[i + j * j] = Math.min(dp[i] + 1, dp[i + j * j]);            }        }        return dp[n];    }}

 

Related Article

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.