var num = 10;
var arr = [];
var arrs = [];
// n的加数组合数组
function summation ( n, m, s ) {
if ( n > 0 ) {
for ( let i = m; i <= n; i++ ) {
arr[s] = i;
summation(n-i, i, s+1 )
}
return;
}
if ( arr[0] == num ) {
return;
}
let resultArr = [];
for (let k = 0; k < s; k++) {
resultArr.push(arr[k])
}
arrs.push(resultArr)
}
// 数组全排序
function permute(nums) {
let res = [];
per(nums, 0, nums.length - 1, res) // 下标从 0 到 length-1
return res;
};
function per(arr, p, q, res) {
// p===q时,数组操作完成
if (p === q) {
res.push([...arr])
} else {
for (let i = p; i <= q; ++i) {
swap(arr, i, p); // 后边的每一位(i)分别与首位(p)交换
per(arr, p + 1, q, res); // 除去第一位,后续部分也分别做全排列
swap(arr, i, p); // 一轮结束后,将arr还原,再进行下一轮操作
}
}
}
// 数值交换
function swap(arr, p, q) {
[arr[p], arr[q]] = [arr[q], arr[p]];
}
// 数组去重
function removeDuplicate(arr) {
let newArr = []
let obj = {}
arr.forEach(item => {
if (!obj[item]) {
newArr.push(item)
obj[item] = true
}
})
return newArr
}
summation(num, 1, 0)
var endRes = [];
for (let i=0; i<arrs.length; i++){
arr = arrs[i]
let permuteResult = permute(arr);
let results = removeDuplicate(permuteResult);
endRes = endRes.concat(results)
}
console.log(endRes)
console