Perfect Squares - Medium - NL

less than 1 minute read

Published:

Question

  • https://leetcode.com/problems/perfect-squares/

Given an integer n, return the least number of perfect square numbers that sum to n.

A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.

Approach

  • DP

Solution

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