279. Perfect Squares
Description
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
Analysis
这道题的意思是给定一个整数,求出它最少多少个平方数之和。
我的做法是利用动态规划。
可以看出当前所求整数的最少平方数之和其实就等于它减去某一个平方数之后得到的那个整数的最少平方数之和加一。
利用这个做法进行循环,不难求出当前整数的最少平方数之和。
Code
#include<iostrem>
using namespace std;
class Solution {
public:
int numSquares(int n) {
int dp[n+1];
dp[0]=0;
dp[1]=1;
for(int i =2;i<=n;++i){
int res= 100000;
int j=1;
while(j*j<=i){
res = min(res,dp[i-j*j]+1);
j++;
}
dp[i] =res;
}
return dp[n];
}
};