首页 > 其他 > 详细

[LeetCode#279] Perfect Squares

时间:2015-09-12 12:04:27      阅读:296      评论:0      收藏:0      [点我收藏+]

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];
    }
}

 

[LeetCode#279] Perfect Squares

原文:http://www.cnblogs.com/airwindow/p/4802728.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!