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.
Example 1:
Input: n = 12 Output: 3 Explanation: 12 = 4 + 4 + 4.
Example 2:
Input: n = 13 Output: 2 Explanation: 13 = 4 + 9.
Constraints:
1 <= n <= 104In this approach, we solve the problem by checking all possible combinations or configurations naively. Although not efficient for large inputs, this approach is often straightforward and can provide insights into the problem structure.
This C solution iterates over all numbers from 0 to n-1, printing each number. It's a simple example of a brute force approach.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n).
Space Complexity: O(1), as no extra space is used other than loop variables.
This approach utilizes dynamic programming to optimize the solution by storing interim results and eliminating redundant calculations seen in a brute force approach. This method can significantly improve efficiency when dealing with complex recursive problems.
This C solution applies dynamic programming to calculate Fibonacci numbers, storing calculated values in the array 'dp' to avoid redundant calculations.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n).
Space Complexity: O(n) due to the storage array.
| Approach | Complexity |
|---|---|
| Approach 1: Brute Force | Time Complexity: O(n). |
| Approach 2: Optimized Solution using Dynamic Programming | Time Complexity: O(n). |
Perfect Squares - Dynamic Programming - Leetcode 279 - Python • NeetCode • 62,696 views views
Watch 9 more video solutions →Practice Perfect Squares with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor