279. Perfect Squares

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

Example 1:

Input: n = 12
Output: 3 
Explanation: 12 = 4 + 4 + 4.

Example 2:

Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.

难度: medium

题目:给定一正整数n,找出其最少个平方数之和为n。

思路:参考 (322. Coin Change)

Runtime: 22 ms, faster than 91.72% of Java online submissions for Perfect Squares.
Memory Usage: 36.6 MB, less than 47.46% of Java online submissions for Perfect Squares.

class Solution {
    public int numSquares(int n) {
        int s = (int) Math.floor(Math.sqrt(n));
        if (s * s == n) {
            return 1;
        }
        
        int[] squares = new int[s];
        int[] nums = new int[n + 1];
        for (int i = 1; i <= s; i++) {
            squares[i - 1] = i * i;
            if (squares[i - 1] < nums.length) {
                nums[squares[i - 1]] = 1;
            }
        }
        
        for (int i = squares[0]; i <= n; i++) {
            if (nums[i] > 0) {
                continue;
            }
            nums[i] = n + 1;
            for (int j = 0; j < squares.length && i - squares[j] >= 0; j++) {
                if (nums[i - squares[j]] > 0) {
                    nums[i] = Math.min(nums[i - squares[j]] + 1, nums[i]);
                }
            }
        }
        
        return nums[n];
    }
}
    原文作者:linm
    原文地址: https://segmentfault.com/a/1190000018386653
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞