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];
        }
    }
  • 相关阅读:
    tkinter gui界面使用调戏妹子
    @property 用法
    @classmehod 用法解析
    python psutil 使用和windows 10 设置
    python 类多重继承问题
    多线程同步引入锁
    Linux—禁止用户SSH登录方法总结
    Linux FTP的主动模式与被动模式
    Java Socket详解
    MySQL学习(一)——创建新用户、数据库、授权
  • 原文地址:https://www.cnblogs.com/airwindow/p/4802728.html
Copyright © 2011-2022 走看看