[LeetCode#279] Perfect Squares

本文探讨了如何找到最少的完美平方数之和来达到给定整数的问题,并提供了动态规划解决方案。

Problem:

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.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Analysis:

Even though I am sure this question must be solved through dynamic programming. I failed in coming up with the right solution initially. 
The problem for me is the right transitional function. 
Instant idea:
min[i] records the least numbers(sum of each square) needed for reaching i. 
j + k == i
min[i] = Math.min(min[j] + min[k]) ( 1<= j < k <= n)
To search the right j and k seems really really costly!

Actually the idea is partially right, but it fails in narrowing down the scope of search optimal combination.
Since the question requires us the target must be consisted of number's square. It means, we actually could use following transitional function.
j^2 + m == i 
min[i] = Math.min(min[m] + 1)

Since m is positive, j^2 must less than i. the search range is actually [1,  sqrt(i)]. 
Why?
We have already computed the min[j] for each j < i, and the square would only need to add extra one number, we are sure there must be a plan to reach i. 

Iff "i" is not the square of any number, we must add a square(j) to reach it!!! 
Thus, we actually must reach i through "j^2 + (i - j^2)", even we may not know what j exact is, we know it must come from [1, sqrt(i)] right!!!

At here, we use a count for this purpose! As a milestone for recording the reached count^2.

Solution:

public class Solution {
    public int numSquares(int n) {
        if (n < 0)
            throw new IllegalArgumentException("n is invalid");
        if (n == 0)
            return 0;
        int[] min = new int[n + 1];
        int count = 1;
        for (int i = 1; i <= n; i++) {
            if (count * count == i) {
                min[i] = 1;
                count++;
            } else{
                min[i] = Integer.MAX_VALUE;
                for (int k = count - 1; k >= 1; k--) {
                    if (min[i-k*k] + 1 < min[i])
                        min[i] = min[i-k*k] + 1;
                }
            }
        }
        return min[n];
    }
}

 

转载于:https://www.cnblogs.com/airwindow/p/4802728.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值