Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 279. Perfect Squares

Rain Hu

279. Perfect Squares


一、題目

Given an integer n, return the least number of perfect square numbers that sum to n. A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.

Example 1:

Example 2:

Constraints:


二、分析

三、解題

1. DP

int numSquares(int n) {
    vector<int> dp(n+1, INT_MAX);
    vector<int> sel;
    for (int i = 1; i <= n; i++) {
        int x = sqrt(i);
        if (x*x == i) {     // 平方數時,增加選擇
            dp[i] = 1;
            sel.push_back(i);
        } else {
            for (int s : sel) {  // 動態規劃轉移方程
                dp[i] = min(dp[i-s]+1, dp[i]);
            }
        }
    }
    return dp[n];
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 1926. Nearest Exit from Entrance in Maze
Next
[LeetCode] 337. House Robber III