permutations and combinations in js All In One
js 中的排列组合
概念
排列
组合
demos
/*
permutations & combinations
排列 & 组合
https://leetcode.com/problems/3sum/
给定一个数字数组,找出有三个元素为一组构成的所有不重复的子数字数组!
*/
// const arr = [1,2,3]
const arr = [1,2,3,4,5]
const arrs = [];
const map = new Map();
for (let i = 0; i < [arr.length - 2]; i++) {
for (let j = i + 1; j < [arr.length - 1]; j++) {
for (let k = i + 2; k < arr.length; k++) {
const value = [arr[i], arr[j], arr[k]];
const key = value.sort((a, b) => a - b > 0 ? 1 : -1).join('');
// 排序,序列化,去除重复组合,如 134 & 143
if(!map.has(key)) {
map.set(key, [...map.get(key), value]);
// map.set(key, value);
if(j !== k) {
// 去除重复数字,如 133
arrs.push(value);
}
}
}
}
}
console.log(`arrs =`, arrs)
/*
$ node ./permutations.js
arrs = [
[ 1, 2, 3 ], [ 1, 2, 4 ],
[ 1, 2, 5 ], [ 1, 3, 4 ],
[ 1, 3, 5 ], [ 1, 4, 5 ],
[ 2, 3, 4 ], [ 2, 3, 5 ],
[ 2, 4, 5 ], [ 3, 4, 5 ]
]
*/
// // const arr = [1,2,3]
// const arr = [1,2,3,4,5]
// const arrs = [];
// for (let i = 0; i < [arr.length - 2]; i++) {
// for (let j = i + 1; j < [arr.length - 1]; j++) {
// for (let k = i + 2; k < arr.length; k++) {
// let f = arr[i];
// let s = arr[j];
// let t = arr[k];
// // console.log(`[f,s,t] =`, [f,s,t], `?`, f,s,t)
// // arrs.push([f,s,t]);
// if(s !== t) {
// arrs.push([f,s,t]);
// }
// }
// }
// }
// console.log(`arrs =`, arrs)