2 回答

TA貢獻1842條經(jīng)驗 獲得超21個贊
const theatreTickets = (array) => {
let combos = []
if(array.length < 2) {
combos.length = 0
}
for(let i = 0; i <= array.length; i++) {
for(let j = i + 1; j <= array.length - 1; j++) {
for(let k = j + 1; k <= array.length - 1; k++) {
combos.push([array[i], array[j], array[k]])
}
}
}
combos = Array.from(new Set(combos.map(JSON.stringify)), JSON.parse)
return combos.length
}
console.log(theatreTickets([1, 2, 1, 1])) // Should Be 3

TA貢獻1796條經(jīng)驗 獲得超4個贊
我認為你需要組合,組合和獨特的算法。它會起作用的。示例如下。
function combine(items, numSubItems) {
var result = [];
var indexes = new Array(numSubItems);
for (var i = 0 ; i < numSubItems; i++) {
indexes[i] = i;
}
while (indexes[0] < (items.length - numSubItems + 1)) {
var v = [];
for (var i = 0 ; i < numSubItems; i++) {
v.push(items[indexes[i]]);
}
result.push(v);
indexes[numSubItems - 1]++;
var l = numSubItems - 1; // reference always is the last position at beginning
while ( (indexes[numSubItems - 1] >= items.length) && (indexes[0] < items.length - numSubItems + 1)) {
l--; // the last position is reached
indexes[l]++;
for (var i = l +1 ; i < numSubItems; i++) {
indexes[i] = indexes[l] + (i - l);
}
}
}
return result;
}
var combinations = combine([1,2,1,1], 3);
console.log([...new Set(combinations.map(x => x.join(",")))]);
combinations = combine([1,2,3,4], 3);
console.log([...new Set(combinations.map(x => x.join(",")))]);
添加回答
舉報