完全平方数

//给定正整数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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值