问题描述
给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。
示例
示例 1:
输入: n = 12
输出: 3
解释: 12 = 4 + 4 + 4.
示例 2:
输入: n = 13
输出: 2
解释: 13 = 4 + 9.
代码
DP
递归不太行,就用了DP
class Solution {
public int numSquares(int n) {
Stack<Integer> queue=new Stack<Integer>();
int[] arr=new int[n+1];
int x=1,i=2;
while(x<=n) {
queue.add(x);
x=i*i;
i++;
}
int min=n;
for(int j=1;j<n+1;j++) {
arr[j]=j;
for(int m=0;m<queue.size();m++) {
if(queue.get(m)<=j)
arr[j]=Math.min(arr[j], arr[j-queue.get(m)]+1);
else
break;
}
}
return arr[n];
}
}
贪心枚举
class Solution {
Set<Integer> square_nums = new HashSet<Integer>();
protected boolean is_divided_by(int n, int count) {
if(count==1)
return square_nums.contains(n);
for(Integer num:square_nums) {
if(n>num&&is_divided_by(n-num, count-1))
return true;
}
return false;
}
public int numSquares(int n) {
square_nums.clear();
for(int i=1;i*i<=n;i++) {
square_nums.add(i*i);
}
int count=1;
for(;count<=n;count++) {
if(is_divided_by(n, count))
return count;
}
return n;
}
}