再present自然数的平方和使用动态规划

编程入门 行业动态 更新时间:2024-10-19 00:25:36
本文介绍了再present自然数的平方和使用动态规划的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

的问题是要找到求和到n个所需平方的最小数

The problem is to find the minimum number of squares required to sum to a number n.

一些例子:

min[ 1] = 1 (1²) min[ 2] = 2 (1² + 1²) min[ 4] = 1 (2²) min[13] = 2 (3² + 2²)

我知道的四平方和定理说在任何自然数可以重新psented作为四个平方和$ P $。

I'm aware of Lagrange's four-square theorem that says that any natural number can be represented as the sum of four squares.

我想解决这个使用DP。

I'm trying to solve this using DP.

这就是我想出了(它不是正确的)

This is what I came up with (its not correct)

min[i] = 1 where i is a square number min[i] = min(min[i - 1] + 1, 1 + min[i - prev]) where prev is a square number < i

什么是正确的DP的方式来解决这个问题?

What is the correct DP way to solve this?

推荐答案

我不知道,如果DP是解决这一问题的最有效的方式,但你问DP。

分钟[I] = MIN(分[我 - 1] + 1,1 +分[我 - preV]),其中$ P $光伏发电是一个平方数&LT;我的 这是接近的,我会写的条件为

min[i] = min(min[i - 1] + 1, 1 + min[i - prev]) where prev is a square number < i This is close, I would write condition as

min[i] = min(1 + min[i - prev]) for each square number 'prev <= i'

请注意,对于每个我您需要检查 $ P $光伏不同的可能值。

Note, that for each i you need to check different possible values of prev.

下面是一个Java简单实现。

Here's simple implementation in Java.

Arrays.fill(min, Integer.MAX_VALUE); min[0] = 0; for (int i = 1; i <= n; ++i) { for (int j = 1; j*j <= i; ++j) { min[i] = Math.min(min[i], min[i - j*j] + 1); } }

更多推荐

再present自然数的平方和使用动态规划

本文发布于:2023-11-29 20:46:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647584.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:平方和   自然数   动态   present

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!