šŸ““
Algorithms
  • Introduction to Data Structures & Algorithms with Leetcode
  • Strings
    • Dutch Flags Problem
      • List Partitoning
    • Counters
      • Majority Vote
      • Removing Parentheses
      • Remove Duplicates from Sorted Array
    • Maths
      • Lone Integer
      • Pigeonhole
      • Check If N and Its Double Exist
      • Find Numbers with Even Number of Digits
    • Two Pointers
      • Remove Element
      • Replace Elements with Greatest Element on Right Side
      • Valid Mountain Array
      • Sort Array by Parity
      • Squares of a Sorted Array
      • Max Consecutive Ones
    • Sliding Window
      • Max Consecutive Ones 3
    • Stacks
      • Balanced Brackets
    • General Strings & Arrays
      • Move Zeros
      • Unique Elements
      • Merge Sorted Array
    • Matrices
      • Valid Square
      • Matrix Search Sequel
  • Trees
    • Untitled
  • Recursion
    • Introduction
    • Backtracking
      • Permutations
  • Dynamic Programming
    • Introduction
    • Minimum (Maximum) Path to Reach a Target
      • Min Cost Climbing Stairs
      • Coin Change
      • Minimum Path Sum
      • Triangle
      • Minimum Cost to Move Chips to The Same Position
      • Consecutive Characters
      • Perfect Squares
    • Distinct Ways
      • Climbing Stairs
      • Unique Paths
      • Number of Dice Rolls with Target Sum
    • Merging Intervals
      • Minimum Cost Tree From Leaf Values
    • DP on Strings
      • Levenshtein Distance
      • Longest Common Subsequence
  • Binary Search
    • Introduction
      • First Bad Version
      • Sqrt(x)
      • Search Insert Position
    • Advanced
      • KoKo Eating Banana
      • Capacity to Ship Packages within D Days
      • Minimum Number of Days to Make m Bouquets
      • Split array largest sum
      • Minimum Number of Days to Make m Bouquets
      • Koko Eating Bananas
      • Find K-th Smallest Pair Distance
      • Ugly Number 3
      • Find the Smallest Divisor Given a Threshold
      • Kth smallest number in multiplication table
  • Graphs
    • Binary Trees
      • Merging Binary Trees
      • Binary Tree Preorder Traversal
      • Binary Tree Postorder Traversal
      • Binary Tree Level Order Traversal
      • Binary Tree Inorder Traversal
      • Symmetric Tree
      • Populating Next Right Pointers in Each Node
      • Populating Next Right Pointers in Each Node II
      • 106. Construct Binary Tree from Inorder and Postorder Traversal
      • Serialise and Deserialise a Linked List
      • Maximum Depth of Binary Tree
      • Lowest Common Ancestor of a Binary Tree
    • n-ary Trees
      • Untitled
      • Minimum Height Trees
    • Binary Search Trees
      • Counting Maximal Value Roots in Binary Tree
      • Count BST nodes in a range
      • Invert a Binary Tree
      • Maximum Difference Between Node and Ancestor
      • Binary Tree Tilt
  • Practice
  • Linked Lists
    • What is a Linked List?
    • Add Two Numbers
      • Add Two Numbers 2
    • Reverse a Linked List
    • Tortoise & Hare Algorithm
      • Middle of the Linked List
  • Bitshifting
    • Introduction
  • Not Done Yet
    • Uncompleted
    • Minimum Cost For Tickets
    • Minimum Falling Path Sum
Powered by GitBook
On this page

Was this helpful?

  1. Dynamic Programming
  2. Minimum (Maximum) Path to Reach a Target

Perfect Squares

PreviousConsecutive CharactersNextDistinct Ways

Last updated 4 years ago

Was this helpful?

Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.

Input: n = 12
Output: 3 
Explanation: 12 = 4 + 4 + 4.

We've seen accessing the last element, or the second to last element in our DP array to perform the recursive step.

What if we wanted to access an element based on a mathematical calculation?

Our base case is that 0 == 0:

  • dp[0] = 0

Now, how do we calculate the recurrence?

Firstly, we need to calculate all possible square numbers up to j. j is not our current index, since any number past half of our index squared will be over it. For example, take 4. Half of 4 is 2. Any number over 2 squared (such as 3^2) will not be equal to 4.

We can use a mathematical calculation for this:

j=int(iāˆ—āˆ—0.5)+1j = int(i**0.5) + 1j=int(iāˆ—āˆ—0.5)+1

To the power of 0.5 is the same as square rooting.

We add 1 to deal with indices and getting the right candidate. If the answer for 4 is 2^2, the answer for 5 will not also be 2^2. So we add one.

There are multiple squares that add up to the index, so we need to select the minimum out of this list.

The dynamic programming comes into play because we do not need to recalculate square numbers. If our number is 4, and our j value is 2 we can use the minimum for 2.

Finally, we add +1 to our solution as the candidate solution.

Example

Input

dp[i]

Result

1

[0, 1]

1

2

[0, 1, 2]

2

3

[0, 1, 2, 3]

3

4

[0, 1, 2, 3, 1]

1

And now the code:

class Solution:
    def numSquares(self, n: int) -> int:
        dp = [0] + [float("inf")] * n
        for i in range(1, n+1):
            dp[i] = min(dp[i-j*j] for j in range(1, int(i**0.5) + 1)) + 1
        return dp[n]

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