LeetCode试炼之路之(2):完全平方数

题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/perfect-squares

给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。

示例 1:

输入: n = 12
输出: 3
解释: 12 = 4 + 4 + 4.
示例 2:

输入: n = 13
输出: 2
解释: 13 = 4 + 9.

解:
思路:本题主要应用到队列及BFS(广度优先算法)

/**
 * 给定正整数 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;
}

猜你喜欢

转载自www.cnblogs.com/yaphse-19/p/12026667.html