Perfect Squares问题及解法

问题描述:

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.


问题分析:

此类问题属于动态规划范畴,对于任意一个数,都可以写成几个完全平方数的形式。

那么我们规定,对于i(i > 1)来说,若i为完全平方数,dp[i] = 1;否则dp[i] = min(dp[i],dp[i - j* j] + 1) (j >=1 && j * j <=  i).


过程详见代码:

class Solution {
public:
    int numSquares(int n) {
		vector dp(n + 1, INT_MAX);
		for (int i = 1; i <= n; i++)
		{
			if (isPS(i)) dp[i] = 1;
			else
			{
				for (int j = 1; j * j <= i; j++)
					{
						dp[i] = min(dp[i], dp[i - j * j] + 1);
					}
			}
		}
		return dp[n];
	}
	bool isPS(int val)
	{
		int t = sqrt(val);
		return t * t == val;
	}
};


你可能感兴趣的:(LeetCode,Medium,DP)