在 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 红包祝福语简短10字
18 周六早晨祝福语简短