# Perfect Squares in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

Suppose we have a positive integer n, find the least number of perfect square numbers whose sum is n. So if the number is 13, then the output is 2, as the numbers are 13 = 9 + 4

To solve this, we will follow these steps −

• create one table for dynamic programming, of length n + 1, and fill it with infinity
• dp := 0
• for i := 1, when i*i <= n
• x = i * i
• for j := x to n
• dp[j] := minimum of dp[j] and 1 + dp[j – x]
• return dp[n]

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
#define INF 1e9
class Solution {
public:
int numSquares(int n) {
vector < int > dp(n+1,INF);
dp = 0;
for(int i =1;i*i<=n;i++){
int x = i*i;
for(int j = x;j<=n;j++){
dp[j] = min(dp[j],1+dp[j-x]);
}
}
return dp[n];
}
};
main(){
Solution ob;
cout << (ob.numSquares(147));
}

## Input

147

## Output

3