leetcode279题 完全平方数 √

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/m0_37719047/article/details/102636343

给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, …)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。

示例 1:

输入: n = 12
输出: 3
解释: 12 = 4 + 4 + 4.

示例 2:

输入: n = 13
输出: 2
解释: 13 = 4 + 9.

class Solution {
 public int numSquares(int n) {
    int[] memo = new int[n+1];
    for (int i = 0;i<n+1;i++)  memo[i]=i;

    for(int i = 2;i<=n;i++){
        for (int j = 1;j*j<=i;j++){
            memo[i] = Math.min(memo[i],memo[i-j*j]+1);
        }
    }
    return memo[n];
}

}

猜你喜欢

转载自blog.csdn.net/m0_37719047/article/details/102636343