您的位置:首页 > Web前端

Perfect Squares

2016-04-27 12:14 267 查看
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.

解法:

dp:

class Solution {
public:
int numSquares(int n) {
int *dp=new int[n+1];
dp[0]=0;
dp[1]=1;
memset(dp,-1,sizeof(int)*(n+1));
return dpFind(n,dp);

}
int dpFind(int n,int* dp)
{
int root=sqrt(n);
if(n==0)
{
return 0;
}
int min=n;
for(int i=1;i<=root;++i )
{
int recu=dp[n-i*i]!=-1?dp[n-i*i]:dpFind(n-i*i,dp);
min=min<recu?min:recu;
}
dp
=min+1;
return min+1;
}
};


BFS:

class Solution
{
public:
int numSquares(int n)
{
if (n <= 0)
{
return 0;
}

// perfectSquares contain all perfect square numbers which
// are smaller than or equal to n.
vector<int> perfectSquares;
// cntPerfectSquares[i - 1] = the least number of perfect
// square numbers which sum to i.
vector<int> cntPerfectSquares(n);

// Get all the perfect square numbers which are smaller than
// or equal to n.
for (int i = 1; i*i <= n; i++)
{
perfectSquares.push_back(i*i);
cntPerfectSquares[i*i - 1] = 1;
}

// If n is a perfect square number, return 1 immediately.
if (perfectSquares.back() == n)
{
return 1;
}

// Consider a graph which consists of number 0, 1,...,n as
// its nodes. Node j is connected to node i via an edge if
// and only if either j = i + (a perfect square number) or
// i = j + (a perfect square number). Starting from node 0,
// do the breadth-first search. If we reach node n at step
// m, then the least number of perfect square numbers which
// sum to n is m. Here since we have already obtained the
// perfect square numbers, we have actually finished the
// search at step 1.
queue<int> searchQ;
for (auto& i : perfectSquares)
{
searchQ.push(i);
}

int currCntPerfectSquares = 1;
while (!searchQ.empty())
{
currCntPerfectSquares++;

int searchQSize = searchQ.size();
for (int i = 0; i < searchQSize; i++)
{
int tmp = searchQ.front();
// Check the neighbors of node tmp which are the sum
// of tmp and a perfect square number.
for (auto& j : perfectSquares)
{
if (tmp + j == n)
{
// We have reached node n.
return currCntPerfectSquares;
}
else if ((tmp + j < n) && (cntPerfectSquares[tmp + j - 1] == 0))
{
// If cntPerfectSquares[tmp + j - 1] > 0, this is not
// the first time that we visit this node and we should
// skip the node (tmp + j).
cntPerfectSquares[tmp + j - 1] = currCntPerfectSquares;
searchQ.push(tmp + j);
}
else if (tmp + j > n)
{
// We don't need to consider the nodes which are greater ]
// than n.
break;
}
}

searchQ.pop();
}
}

return 0;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: