Leetcode 279 Perfect Squares

    xiaoxiao2021-03-25  82

    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.

    这是一个 dynamic programming 的问题

    初次接触

    可以理解为一个规划的策略问题

    参考动态规划

    在这个问题里面,给定一个数n,可能包含的最大的平方数有限,但是却可以有不同的组合。

    题目的要求就是寻找min也即是能大就不小

    其实是需要递归遍历找出最小值的问题

    在DP里面有一个很重要的思想就是存储中间值,这样就不需要进行重复的计算

    public class Solution { public int numSquares(int n) { int[] dp = new int[n + 1]; Arrays.fill(dp, Integer.MAX_VALUE); dp[0] = 0; for(int i = 1; i <= n; ++i) { int min = Integer.MAX_VALUE; int j = 1; while(i - j*j >= 0) { min = Math.min(min, dp[i - j*j] + 1); ++j; } dp[i] = min; } return dp[n]; } }

    转载请注明原文地址: https://ju.6miu.com/read-38711.html

    最新回复(0)