Perfect Squares
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...
) which sum to n.
Example 1:
Input: n =12
Output: 3 Explanation:12 = 4 + 4 + 4.
Example 2:
Input: n =13
Output: 2 Explanation:13 = 4 + 9.
class Solution {
public int numSquares(int n) {
int[] dp = new int[n + 1];
int near, min;
for (int i = 1; i <= n; i++) {
near = (int) Math.sqrt(i);
min = dp[i - 1];
for (int j = near; j > 0; j--) {
min = Math.min(dp[i - j * j], min);
}
dp[i] = min + 1;
}
return dp[n];
}
}
Here, we are going to solve problem using bottom up DP(Dynamic Programming).
1) Initialize dp array having size of n+1.
2) i variable iterates from 1 to n and for each i values we find nearest square number (near variable).
3) j iterates from near to 1 and for each j value we find Math.min(dp[i - j * j], min) . After finding min value, store dp[i] as min+1.
4) Finally, dp[n] contains minimum number of perfect square sum to reach n.
[NOTE]If you take any n, dp[0] to dp[4] have same values.
Consider following example,
For n = 6, O/P is 3 (i.e 1+1+4)
i=1, i=2, i=3, i=4, i=5 i=6
near =1 near = 4 near = 9 near = 16 near = 25 near = 36
min = 0 min = 1 min = 2 min = 3 min = 1 min = 2
dp[1]= 1 dp[2] = 2 dp[3] = 3 dp[4] = 4 dp[5] = 2 dp[6] = 3
Related Posts:
Click here for May month challenges with solution and explanation
Click here for April month challenges with solution and explanation
Click here for May month challenges with solution and explanation
Click here for April month challenges with solution and explanation
Click Follow button to receive updates from us instantly.
Please let us know about your views in comment section.
Comments
Post a Comment