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.

    class Solution {
    public:
        int getMaximumSquare(int n){
            int ret = (int)sqrt(n);
            return ret;
        }
        int dfs(int load, vector<int> &dp){
            if(dp[load]) return dp[load];
            if(load == 0){
                return 0;
            }
            
            int next = getMaximumSquare(load);
            int Min = numeric_limits<int>::max();
            for(int v=next;v>=1;v--){
                if(load-v*v >= 0){
                    Min = min(Min, dfs(load-v*v, dp));
                } 
            }
            dp[load] = Min + 1;
            return dp[load];
        }
        int numSquares(int n) {
            vector<int> dp(n+1);
            for(int i=0;i<dp.size();++i) dp[i] = 0;
            
            dp[n] = dfs(n, dp);
            return dp[n];
        }
    };
     
  • 相关阅读:
    Hyperion Planning 表单数据验证功能实现
    类型别名
    内联函数和constexpr函数
    强制类型转换
    当函数返回值是引用
    左值和右值
    const形参和实参
    const限定符
    auto与decltype
    局部对象
  • 原文地址:https://www.cnblogs.com/fu11211129/p/4930018.html
Copyright © 2011-2022 走看看