zoukankan      html  css  js  c++  java
  • [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];
        }
    }
  • 相关阅读:
    Chapter 4 持久存储数据对象
    pyhton Chapter3 读文件
    python笔记1
    C#读写txt文件
    机器学习第一讲
    Json对象
    表单加载
    多列树
    Java 基础【11】@注解
    Java 基础【06】复合赋值运算
  • 原文地址:https://www.cnblogs.com/airwindow/p/4802728.html
Copyright © 2011-2022 走看看