Topic Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/perfect-squares
Given a positive integer n, to find the perfect square number (such as 1, 4, 9, 16, ...) so that their sum equal to n. At least you need to make a perfect square of the number and composition.
Example 1:
Input: n-12 =
Output: 3
Explanation: 12 + 4 + 4 = 4.
Example 2:
Input: n-13 =
Output: 2
Explanation: 13 + 4 = 9.
Solution:
Ideas: The main question applied to the queue and BFS (breadth-first algorithm)
/**
* 给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。
*/
public static int numSquares(int n) {
List<Integer> list = findList(n);
int count = 0;
//从list中获取一个数与总数相加,查询是否能找到解
if(0 ==n){
return 0;
}
List<Integer> plus = list;
List<Integer> sums = new ArrayList<Integer>();
sums.add(0);
while(count<n){
List<Integer> temp = new ArrayList<Integer>();
for(int sum :sums) {
for (int i : list) {
if (n == (sum + i)) {
count++;
return count;
}
temp.add(sum+i);
}
}
sums.addAll(temp);
//遍历完之后还未找到,则增加计算次数
count++;
}
return -1;
}
public static List<Integer> findList(int max){
List<Integer> list = new ArrayList<Integer>();
for(int i=1;i*i<=max;i++){
list.add(i*i);
}
return list;
}