[WXM] LeetCode 279. Perfect Squares C++

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.

Approach

  1. 题目大意一个数被平方数组和最少的数量为多少,这道题用递推的方式是最快的,首先一个数被平方数组合最多的数量就是自己本身,也就是全部为1,所以我们很容意想到递推公式为dp[i]=min(dp[i],dp[i-s]+1)dp[i]就是某个数他自己本身,dp[i-s]然后有平方数小于它,我们先减这个数得到另一个数也是自己本身然后加一,因为这个新的数到达这个数相差为1,理解了递推公式,也就明白大概思路,剩余看怎么写比较重要。
  2. [WXM] LeetCode 377. Combination Sum IV C++ 这道题也挺类似的,也是用到递推的方法。

Code

class Solution {
public:
    int numSquares(int n) {
        if (n == 0 || n == 1)return 1;
        vector<int>dp(n + 1, 0);
        dp[0] = 0;
        dp[1] = 1;
        for (int i = 2; i <= n; i++) {
            dp[i] = i;
            for (int j = 1; j*j<=i;j++) {
                dp[i] = min(dp[i], dp[i - j*j] + 1);
            }
        }
        return dp[n];
    }
};

猜你喜欢

转载自blog.csdn.net/WX_ming/article/details/82050232