Javascript 以JS格式将纸张切割成最少的正方形
我想把算法从 在javascript中 我能够轻松地在js()中翻译第一个算法,但是贪婪的方法不够精确 我在js和递归编程方面遇到了一些问题,在我第一次尝试时,我得到了最大调用堆栈大小超出错误,因此我尝试使用Javascript 以JS格式将纸张切割成最少的正方形,javascript,algorithm,Javascript,Algorithm,我想把算法从 在javascript中 我能够轻松地在js()中翻译第一个算法,但是贪婪的方法不够精确 我在js和递归编程方面遇到了一些问题,在我第一次尝试时,我得到了最大调用堆栈大小超出错误,因此我尝试使用节点--stack size=10000,但在这种情况下,脚本没有输出任何内容 这就是我现在拥有的: // JS program to find minimum // number of squares // to cut a paper using Dynamic Programm
节点--stack size=10000
,但在这种情况下,脚本没有输出任何内容
这就是我现在拥有的:
// JS program to find minimum
// number of squares
// to cut a paper using Dynamic Programming
const MAX = 300
let dp = new Array(MAX);
for (let i = 0; i < dp.length; i++) {
dp[i] = new Array(MAX).fill(0);
}
// Returns min number of squares needed
function minimumSquare(m, n) {
// Initializing max values to
// vertical_min
// and horizontal_min
let vertical_min = 10000000000
let horizontal_min = 10000000000
// If the given rectangle is
// already a square
if (m === n) {
return 1
}
// If the answer for the given rectangle is
// previously calculated return that answer
if (dp[m][n] !== 0) {
return dp[m][n]
}
// The rectangle is cut horizontally and
// vertically into two parts and the cut
// with minimum value is found for every
// recursive call.
for (let i=1; i<m/2+1; i++) {
// Calculating the minimum answer for the
// rectangles with width equal to n and length
// less than m for finding the cut point for
// the minimum answer
horizontal_min = Math.min(minimumSquare(i, n) + minimumSquare(m-i, n), horizontal_min)
}
for (let j=1; j<n/2+1; j++) {
// Calculating the minimum answer for the
// rectangles with width equal to n and length
// less than m for finding the cut point for
// the minimum answer
vertical_min = Math.min(minimumSquare(m, j) + minimumSquare(m, n-j), vertical_min)
}
// Minimum of the vertical cut or horizontal
// cut to form a square is the answer
dp[m][n] = Math.min(vertical_min, horizontal_min)
return dp[m][n]
}
// Driver code
let m = 30
let n = 35
console.log(minimumSquare(m, n))
//This code is contributed by sahilshelangia
//JS程序找到最小值
//方块数
//用动态规划法剪纸
常数最大值=300
设dp=新阵列(最大值);
for(设i=0;i 对于(设i=1;i我添加了两个新条件来解决问题
- 如果m可被n整除,则返回值m/n
- 如果n可被m整除,则返回值n/m
const MAX=300
设dp=新阵列(最大值);
for(设i=0;i 为了(让我=1;我为没有尝试这个而感到愚蠢!非常感谢!