Created
November 11, 2017 21:20
-
-
Save shailrshah/4e3dba68176df36872e4af39033e9aa3 to your computer and use it in GitHub Desktop.
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// dp[0] = 0 | |
// dp[i] = min(dp[n-i*i] + 1) where i > 0 && n-i*i >=0 | |
public int numSquares(int n) { | |
int dp[] = new int[n+1]; | |
dp[0] = 0; | |
for(int i = 1; i <= n; i++) { | |
int min = Integer.MAX_VALUE; | |
int j = 1; | |
while(i - j*j >= 0) { | |
min = Math.min(min, dp[i - j*j] + 1); | |
j++; | |
} | |
dp[i] = min; | |
} | |
return dp[n]; | |
} |
dp[] = [0 1 2 3 1 2 3 4 2 1 2 3 3 3...]
@shailrshah. I would really appreciate if can explain your thought process explicitly?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For every i, it must be the sum of i-j^2 and a perfect square j^2