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
.
solution:
similar to 0/1 knapsack problem, use dp to solve this.
public class Solution { public int numSquares(int n) { int[] dp = new int[n+1]; dp[1] = 1; for(int i=2;i<=n;i++){ int min = Integer.MAX_VALUE; int j = 1; while(j*j<=i) { if(j*j == i){ min = 1; break; } min = Math.min(min, dp[i-j*j]+1); ++j; } dp[i] = min; } return dp[n]; } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
[LeetCode 279] Perfect Squares
原文地址:http://blog.csdn.net/sbitswc/article/details/48545137