Title: Perfect Squares Source: leetcode.com
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
.
Java solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
/* https://leetcode.com/problems/perfect-squares/ */ class PerfectSquares { public static void main(String args[]) { PerfectSquares ps = new PerfectSquares(); System.out.println(ps.numSquares(12)); } public int numSquares(int n) { int[] dp = new int[n+1]; for(int i=1;i<=n;i++) { int min = Integer.MAX_VALUE; for(int j=1;j<=(int)Math.sqrt(i);j++) { min = Math.min(min, dp[i - j*j]+1); } dp[i] = min; } return dp[n]; } } |