[LeetCode]Perfect Squares

来源:互联网 发布:软件测试 招聘 编辑:程序博客网 时间:2024/06/05 09:44

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.

动态规划。


class Solution {public:    int numSquares(int n) {        vector<int> Dp(n+1);        Dp[0] = 0;        Dp[1] = 1;        for(int i=1;i<n+1;++i){            int sqrtindex = sqrt(i);            Dp[i] = i;            for(int j=1;j<sqrtindex+1;++j){                if(Dp[i]>Dp[i-j*j]+1){                    Dp[i] = Dp[i-j*j]+1;                }            }        }        return Dp[n];    }};


0 0