Leetcode Perfect Squares 相关代码,使用dp算法完成,利用其最有子结构特性,算法复杂度为O(n ^ 3/2)。代码如下,以及相关测试:
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int numSquares(int n) {
vector<int> re(n + 1, 0);
for (int i = 1; i * i <= n; i ++) {
re[i * i] = 1;
}
for (int i = 1; i <= n; i ++) {
if (re[i] != 1) {
int min = i;
for (int j = 1; j * j < i; j ++) {
int temp = re[j * j] + re[i - j * j];
min = temp < min? temp : min;
}
re[i] = min;
}
}
return re[n];
}
};
int main(int argc, char * argv[]) {
Solution so;
int re = so.numSquares(13);
cout<<"result : "<<re<<endl;
return 0;
}