//给定正整数n,找到若干个完全平方数(比如1, 4, 9, 16,,)使得它们的和等于n。你需要让组成和的完全平方数的个数最少。
//给你一个整数n,返回和为n的完全平方数的最少数量。
#include <iostream>
#include <vector>
using namespace std;
int numSquares(int targetValue)
{
//先设一个一维数组,用于存放可以组成targetValue的所有的完全平方数,由于targetValue是一个正整数,0加任何数无意义,
//所以完全平方数从1开始记录
vector<int> squaresVec;
for (int i = 1; i <= targetValue; i++)
{
int currentSquareValue = i * i;
if (currentSquareValue < targetValue)
{
squaresVec.push_back(currentSquareValue);
}
}
//创建dp数组,dp[i]表示组成数字i的最小的完全平方数的个数,所有元素初始化为-1,表示当前值无法通过小于等于它的完全平方数拼凑
vector<int>dp(targetValue + 1, -1);
// dp[0]表示数字0需要完全平方数的最少数量,数量非负的,即0
dp[0] = 0;
//填充剩余的dp数组
for (int i = 1; i <= targetValue; i++)
{
//当完全平方数的值squaresVec[j]大于i的值的时候,无法用来拼凑i值,没必要继续下去得到dp[i]
for (int j = 0; j < squaresVec.size(); j++)
{
if (squaresVec[j] > i)
{
break;
}
//到了这里,看dp[i]的值是否可以更新,观察 dp[i - squaresVec[j]]可知,当i与squaresVec[j]相同时,dp[i] = dp[0] + 1 = 0 + 1 = 1
if (dp[i] == -1 || dp[i] > dp[i - squaresVec[j]] + 1)
{
dp[i] = dp[i - squaresVec[j]] + 1;
}
}
}
return dp[targetValue];
}
int main()
{
int targetValue = 18;
int result = numSquares(targetValue);
cout << result << endl;
}
完全平方数
于 2023-05-18 14:53:45 首次发布