首页 > 代码库 > LeetCode 279. Perfect Squares

LeetCode 279. Perfect Squares

Question:

Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.

For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.

 

Code:

public class Solution {
    public int numSquares(int n) {
        Queue<Map.Entry<Integer, Integer>> queue = new LinkedList<>();
        queue.add(new java.util.AbstractMap.SimpleEntry<Integer, Integer>(n, 0));

        boolean[] visited = new boolean[n+1];
        visited[n] = true;
        while (!queue.isEmpty()){
            Map.Entry<Integer, Integer> entry = queue.poll();
            int num = entry.getKey();
            int step = entry.getValue();

            for (int i = 1; ; i++) {
                int a = num - i*i;
                if(a < 0){
                    break;
                }
                if(a == 0){
                    return step + 1;
                }
                if (!visited[a]){
                    queue.add(new java.util.AbstractMap.SimpleEntry<Integer, Integer>(a, step + 1));
                    visited[a] = true;
                }
            }

        }
        return 0;
    }
}

 

看到其他网友提交的代码,有用动态规划的,感觉比自己写的思路简单的多,也贴出来学习

public class Solution {
    
    public int numSquares(int n) {
        if (n < 2) return 1;
        
        int[] dp = new int[n+1];
        for (int i = 1; i <= n; i ++) {
            int val = Integer.MAX_VALUE;
            for (int j = 1; j * j <= i; j ++) {
                val = Math.min(val, dp[i-j*j]);
            }
            dp[i] = val + 1;
        }
        
        return dp[n];
    }
}

 

LeetCode 279. Perfect Squares