1+ #include < iostream>
2+ #include < vector>
3+ using namespace std ;
4+
5+ /*
6+ problem link: https://leetcode.com/problems/perfect-squares/description/
7+ Given an integer n, return the least number of perfect square numbers that sum to n.
8+
9+ A perfect square is an integer that is the square of an integer; in other words, it is the
10+ product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3
11+ and 11 are not.
12+
13+ Example 1:
14+
15+ Input: n = 12
16+ Output: 3
17+ Explanation: 12 = 4 + 4 + 4.
18+
19+ Example 2:
20+
21+ Input: n = 13
22+ Output: 2
23+ Explanation: 13 = 4 + 9.
24+ */
25+
26+ class Solution
27+ {
28+ public:
29+ int numSquares (int n)
30+ {
31+ // Create a vector to store all perfect squares
32+ vector<int > vectorOfPerfectSquare;
33+
34+ // Loop through the numbers from 1 to the square root of n
35+ for (int i = 1 ; i * i <= n; i++)
36+ {
37+ // If the square of i is a perfect square, push it to the vector v
38+ vectorOfPerfectSquare.push_back (i * i);
39+ }
40+
41+ // If n is equal to 1, return 1
42+ if (n == 1 )
43+ {
44+ return 1 ;
45+ }
46+
47+ // Define a variable Max equal to n + 1
48+ int Max = n + 1 ;
49+ // Create a vector dp with length equal to n + 1 and fill it with Max
50+ vector<int > dp (n + 1 , Max);
51+ // Initialize the first element of dp as 0
52+ dp[0 ] = 0 ;
53+ // Loop through n from 1 to n
54+ for (int i = 1 ; i <= n; i++)
55+ {
56+ // Loop through the vectorOfPerfectSquare
57+ for (int j = 0 ; j < vectorOfPerfectSquare.size (); j++)
58+ {
59+ // If the value of i is greater than or equal to the current coin value
60+ if (i - vectorOfPerfectSquare[j] >= 0 )
61+ {
62+ // Update the value of dp[i] to the minimum of dp[i] and dp[i-vectorOfPerfectSquare[j]] + 1
63+ dp[i] = min (dp[i], dp[i - vectorOfPerfectSquare[j]] + 1 );
64+ }
65+ }
66+ }
67+ // Return the value of dp[n] if it is less than or equal to n, else return -1
68+ return dp[n] > n ? -1 : dp[n];
69+ }
70+ };
0 commit comments