1. 程式人生 > >279. Perfect Squares

279. 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.

Example 1:

Input: n = 12
Output: 3 
Explanation: 12 = 4 + 4 + 4.

Example 2:

Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.

分析:

比如設13為根節點,13 – 3 * 3 = 4, 13 – 2 * 2 = 9, 13 – 1 * 1 = 12,

4, 9, 12就是root的三個child,是第二層;

再下面一層,4 – 2 * 2 = 0, 4 – 1 * 1 = 3,4的child是0和3

因為發現了一個0,說明此時該層就為該數最少需要的平方和數字的個數

程式碼實現:

class Solution{
public:
	
	int numSquares(int n) 
	{
		queue<int> q;
		int ans = 1;
		q.push(n);
		while (!q.empty())
		{
			int size = q.size();
			while (size--)
			{
				int front = q.front();
				q.pop();
				for (size_t i = sqrt(front); i > 0; i--)
				{
					if (i*i == front)
						return ans;
					q.push((front - i * i));
				}
			}
			ans++;
		}
	}
};