[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

转载于:https://www.cnblogs.com/lz87/p/7498484.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值