[LintCode] 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

Given n = 12, return 3 because 12 = 4 + 4 + 4
Given n = 13, return 2 because 13 = 4 + 9

 

Recursion

base case f(0) = 0;

f(n) = min(f(n - i * i)) + 1,  for i * i <= n;

 1  public int numSquares(int n) {
 2     if(n == 0) {
 3         return 0;
 4     } 
 5     int minNum = Integer.MAX_VALUE;
 6     for(int i = 1; i * i <= n; i++) {
 7         minNum = Math.min(minNum, 1 + numSquares(n - i * i));
 8     }
 9     return minNum;
10  }

 

Dynamic Programming Solution

State: dp[i]: the least number of perfect sqaure numbers that sum to i.

Function: dp[i] = 1 + min(dp[i - j * j], for all j that satisfies j * j <= i); 

Initialization: dp[i * i] = 1, for i * i <= n, the rest of dp[i] = Integer.MAX_VALUE.

Answer: dp[n]

 1 public class Solution {
 2     /**
 3      * @param n a positive integer
 4      * @return an integer
 5      */
 6     public int numSquares(int n) {
 7         int[] dp = new int[n + 1];
 8         Arrays.fill(dp, Integer.MAX_VALUE);
 9         dp[0] = 0;
10         for(int i = 1; i * i <= n; i++) {
11             dp[i * i] = 1;
12         }
13 
14         for (int i = 1; i <= n; i++) {
15             for (int j = 1; j * j <= i; j++) {
16                 dp[i] = Math.min(dp[i], dp[i - j * j] + 1);
17             }
18         }
19         return dp[n];
20     }
21 }

 

 

Related Problems

Check Sum of Square Numbers

Ugly Number II

posted @ 2017-11-12 14:27  Review->Improve  阅读(188)  评论(0编辑  收藏  举报