杨辉三角的格式如下:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
......
解决方式:递归
// m是行,n是列
function combination(m,n){
if(n === 0) return 1; // 每一行的第一个,都是1
else if( m === n) return 1; // 出去第一行,每行的最后一个元素
else return combination(m-1, n-1) + combination(m-1, n); // 每行的其他元素
}
// 一共有m行
function print(m){
let res = []
for(let i=0; i<m; i++){
let arr = [];
for(let j=0; j<=i; j++){
arr.push(combination(i,j))
}
res.push(arr)
}
return res
}
console.log(print(13));
网友评论