动态规划-给定一个正整数n,求和为n的最小个数完美平方数(例如,1,4,9,16,…)。

21 篇文章 0 订阅
21 篇文章 0 订阅
package com.algorithm.dynamicprogramming;

/**
 * 算法描述:给定一个正整数n,求和为n的最小个数完美平方数(例如,1,4,9,16,…)。 
 * Example 1:
 * Input: n = 12
 * Output: 3 Explanation: 12 = 4 + 4 + 4. 
 * 
 * Example 2:
 * Input: n = 13
 * Output: 2 Explanation: 13 = 4 + 9.
 * @author rich
 *
 */
public class PerfectSquares {

    public static void main(String[] args) {
        System.out.println(perfectSquares(4));
    }
    /**
     * 算法分析:当 
     * n = 1 1
     * n = 2 1+1 
     * n = 3 1+1+1 
     * n = 4 1+1+1+1 
     * n = 5 1+4 
     * n = 6 1+1+4 
     * n = 7 1+1+1+4
     * n = 8 4+4
     * n = 9 1+4+4
     * n = 10 1+1+4+4
     * n = 11 1+1+1+4
     * n = 12 4+4+4
     * n = 13 4+9
     * @param n
     * @return
     */
    public static int perfectSquares(int n) {
        int[] memo = new int[n+1];
        if (n == 1) return 1;
        memo[0] = 0;
        memo[1] = 1;
        for (int i = 2;i<=n;i++) {
            memo[i] = i;
            for (int j = 1;j*j <= i;j++) {
                memo[i] = Math.min(memo[i], memo[i-j*j]+1);
            }
        }
        return memo[n];
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

走在时光柱上的程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值