Skip to content

Instantly share code, notes, and snippets.

@shailrshah
Created November 11, 2017 21:20
Show Gist options
  • Save shailrshah/4e3dba68176df36872e4af39033e9aa3 to your computer and use it in GitHub Desktop.
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.
// 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];
}
@shailrshah
Copy link
Author

shailrshah commented Nov 13, 2017

For every i, it must be the sum of i-j^2 and a perfect square j^2

@shailrshah
Copy link
Author

dp[] = [0 1 2 3 1 2 3 4 2 1 2 3 3 3...]

@johnoyegbite
Copy link

@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