在 JavaScript 中构建一个特定大小的数组,其中连续元素和是完美的平方
我们需要编写一个接受数字n的JavaScript函数。我们的函数应该返回一个以某种方式排列的整数数组1..n,使得每2个连续数字的和是一个正方形。
示例
此代码将是-
const n = 15;
const buildSquaresArray = (n = 1, res = []) => {
const helper = (res, set, n) => {
if(set.size === n){
return true;
};
for(let i = 1; i <= n; i++){
if (set.has(i)){
continue;
};
if(res.length && Math.sqrt(res[0] + i) % 1 !== 0){
continue;
};
set.add(i);
res.unshift(i);
if(helper(res,set,n)){
return true;
}
res.shift();
set.delete(i);
};
return false;
};
return helper(res,new Set(),n) ? res : false;
};
console.log(buildSquaresArray(n));输出结果控制台中的输出将是-
[ 9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8 ]
热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短