zoukankan      html  css  js  c++  java
  • LeetCode 279. Perfect Squares

    原题链接在这里:https://leetcode.com/problems/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.

    For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.

    题解:

    Let dp[i] denotes the least number of perfect squares sum to i.

    Then for all the candiates smaller than i, if the difference between i and candidate is perfect square, then update the dp[candidate]+1. Maintain the smallest.

    Thne how to make sure the difference is perfect square.

    Let candidate = i - j*j.

    Time Complexity: O(nlogn).

    Space: O(n).

    AC Java:

     1 class Solution {
     2     public int numSquares(int n) {
     3         int [] dp = new int[n+1];
     4         for(int i = 1; i<=n; i++){
     5             dp[i] = i;
     6             for(int j = 0; i-j*j>=0; j++){
     7                 dp[i] = Math.min(dp[i], dp[i-j*j]+1);
     8             }
     9         }
    10         
    11         return dp[n];
    12     }
    13 }

    Could also do it from head to tail.

    初始化i*i的位置为1, 然后对i + j*j 更新min(dp[i+j*j], dp[i] + 1).

    Time Complexity: O(nlogn). Space: O(n).

    AC Java:

     1 public class Solution {
     2     public int numSquares(int n) {
     3         if(n < 0){
     4             return 0;
     5         }
     6         int [] dp = new int[n+1];
     7         Arrays.fill(dp, Integer.MAX_VALUE);
     8         for(int i = 0; i*i <= n; i++){
     9             dp[i*i] = 1;
    10         }
    11         for(int i = 1; i<=n; i++){
    12             for(int j = 1; i+j*j<=n; j++){
    13                 dp[i+j*j] = Math.min(dp[i+j*j], dp[i]+1);
    14             }
    15         }
    16         return dp[n];
    17     }
    18 }

    Count Primes类似. 

  • 相关阅读:
    获取当前时区时间
    python lambda表达式详解
    Odoo 12开发之开发环境准备
    初步了解odoo12
    web前端面试题
    实现一个优先级队列
    面试题
    python读取和生成excel文件
    Django基础
    virtualenv
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4824956.html
Copyright © 2011-2022 走看看