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)