package DP;
public class _279_PerfectSquares {
/**
* 1.递归+dfs
* 13
* /1 |4 \9
* 12 9 4
* /1 |4 \9 /1 \4
* 11 8 3 3 0
* @param n
* @return
*/
public int helper1(int n){
if (n == 0){
return 0;
}
int res = Integer.MAX_VALUE;
for (int i = 1; i*i <= n; i++){
res = Math.min(res, helper1(n-i*i) + 1);
}
return res;
}
/**
* 2. 递归+记忆化
*/
public int helper2(int n, int[] mem){
if (n == 0){
return 0;
}
if (mem[n] != 0){
return mem[n];
}
int res = Integer.MAX_VALUE;
for (int i = 1; i*i <= n; i++){
res = Math.min(res, helper2(n-i*i, mem) + 1);
}
mem[n] = res;
return res;
}
/**
* 3. dp
* 1. 初始化长度为n+1的dp数组,初始值为0
* 2. dp[0] = 0
* 3. 遍历数组,dp[i] = i。如i=4, 4 = 1+1+1+1,最多为4
* 5. 状态转移:dp[i] = min{dp[i], dp[i - j*j] + 1}, j >= 1 && j*j <= i.
*/
public int helper3(int n){
int[] dp = new int[n+1];
for (int i = 0; i <= n; i++){
dp[i] = i;
}
for (int i = 2; i <= n; i++){
for (int j = 1; j*j <= i; j++){
dp[i] = Math.min(dp[i], dp[i-j*j] + 1);
}
}
return dp[n];
}
/**
*
* @param n
* @return
*/
public int numSquares(int n){
// return helper1(n);
// int[] mem = new int[n+1];
// return helper2(n, mem);
return helper3(n);
}
public static void main(String[] args) {
System.out.println(new _279_PerfectSquares().numSquares(13));
}
}
Leetcode_279_PerfectSquares_按平方数来分割整数
最新推荐文章于 2021-03-08 18:54:08 发布