Friday, 21 October 2016

Perfect Squares (LeetCode)

Problem: Perfect Squares
Given a positive integer n, find the least number of perfect square numbers which sum to n.

class Solution {
public:
    int dp[100000];
    int numSquares(int n) {
        memset(dp, -1, sizeof(dp));
        return func(n);
        
    }
    int func(int n)
    {
        if(n<=0) return 0;
        
        if(dp[n]!=-1) return dp[n];
        int ret=1e9;
        for(int i=1;i*i<=n;i++)
            ret=min(ret, func(n-i*i)+1);
            
        return dp[n]=ret;
    }
};

No comments:

Post a Comment