[Leetcode] #279 Perfect Squares (BFS, DP)

1192 단어 LeetcodeLeetCode

Discription


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 .

Solution

int numSquares(int n) {  //BFS
	int sn = sqrt(n);
	if (sn*sn == n)
		return 1;
	vector square, state(n + 1, 0);
	queue que;
	for (int i = 1; i <= sn; i++){	
		square.push_back(i*i);
		que.push(i*i);
		state[i*i] = 1;
	}
	while (!que.empty()){
		int x = que.front();
		que.pop();
		for (int i : square){
			if (x + i <= n && state[x + i] == 0){
				state[x + i] = state[x] + 1;
				que.push(x + i);
			}			
		}
	}
	return state[n];
}
int numSquares(int n) { //DP
	vector dp(n+1,0);
	for (int i = 1; i <= n; i++){
		int square = INT_MAX;
		for (int j = 1; j*j <= i; j++)
			square = min(square, dp[i - j*j] + 1);
		dp[i] = square;
	}
	return dp[n];
}
GitHub-Leetcode: https://github.com/wenwu313/LeetCode

좋은 웹페이지 즐겨찾기