【leetcode】Perfect Squares (#279)
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, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.
解析:
利用动态规划解决此问题:对于要求的当前节点而言都是从前面的节点转移过来的,只是这些转移节点并非一个,而是多个,比如1*1,2*2,3*3,,,那么相应的res[i-1]、res[i-4]、res[i-9]等等都是转移点。从这些候选项中找到最小的那个,然后加1即可。
算法实现代码:
//#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(13); return 0; }