题解 | #最少的完全平方数#
最少的完全平方数
http://www.nowcoder.com/practice/4b2f5d4c00f44a92845bdad633965c04
完全背包问题,体积为n,不断往背包里面放i * i
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
// init
// dp[i] = dp[i - j * j] + 1
int[] dp = new int[n + 1];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
if (j * j <= i) {
dp[i] = Math.min(dp[i], dp[i - j * j] + 1);
}
}
}
// 恰好体积为n
System.out.println(dp[n]);
}
}