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

xiaoxiao2021-02-28  121

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<int> square, state(n + 1, 0); queue<int> 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<int> 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

转载请注明原文地址: https://www.6miu.com/read-69688.html

最新回复(0)