[leetcode]279. Perfect Squares

[leetcode]279. Perfect Squares


Analysis

missing—— [每天刷题并不难0.0]

Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, …) which sum to n.
在这里插入图片描述

Explanation:

Dynamic programing,res[i] represent the least number of perfect square numbers which sum to i. For each i<=n, it must be the sum of some number (i-jj) and a perfect square number (jj).

Implement

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

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/87929238