"Leetcode" Perfect squares (#279)

Source: Internet
Author: User

Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, ...) which Sum to n. For example, given n = A, return 3 because 12 = 4 + 4 + 4; Given n = 13, return 2 because = 4 + 9.

Analytical:

Use dynamic planning to solve this problem: for the required current node is transferred from the previous node, but these transfer nodes are not one, but many, such as 1*1,2*2,3*3,, then the corresponding res[i-1], res[i-4], res[i-9] and so are the transfer points. Find the smallest one from these candidates and add 1.

Algorithm implementation code:

#include "stdafx.h" #include <iostream> #include <cstdio> #include <climits> #include <ctime> #include <algorithm> #include <vector> #include <stack> #include <queue> #include <cstdlib > #include <windows.h> #include <string> #include <cstring> #include <cmath>using namespace Std;class Solution {public:    int numsquares (int n) {        vector<int> res (n + 1);        for (int i = 0; I <= N; ++i) {            res[i] = i;            for (int j = 1; J * J <= i; ++j) {                Res[i] = min (Res[i-j * j] + 1, res[i]);            }        }        return res[n];}    ; int main () {solution s;cout<<s.numsquares (+); return 0;}

  

"Leetcode" Perfect squares (#279)

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.