๋ณธ๋ฌธ์œผ๋กœ ๊ฑด๋„ˆ๋›ฐ๊ธฐ

42578. ์œ„์žฅ

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์œ„์žฅ


๋ฌธ์ œ ์œ ํ˜•๋‚œ์ด๋„๊ฑธ๋ฆฐ ์‹œ๊ฐ„ํ•ด๊ฒฐ ์œ ๋ฌด(โœ…/โŒ)
ํ•ด์‹œlv.22์‹œ๊ฐ„โœ…

์„ค๊ณ„ ๋ฐฉ๋ฒ•#

์‹คํŒจ#

  • Map ์ž๋ฃŒ๊ตฌ์กฐ์— ์ข…๋ฅ˜ : ์˜ท ๊ฐœ์ˆ˜๋ฅผ ๋‹ด๋Š”๋‹ค.

  • ๊ฐ€๋Šฅํ•œ ๋ชจ๋“  ์˜์ƒ ์กฐํ•ฉ์„ ์ฐพ๋Š”๋‹ค. getAllCombinations([...hashMap.values()])

  • ์˜์ƒ์˜ ์ข…๋ฅ˜๊ฐ€ ํ•˜๋‚˜๋ผ๋ฉด ์˜ท ๊ฐœ์ˆ˜๋ฅผ ๋”ํ•˜๊ณ , ์˜์ƒ์˜ ์ข…๋ฅ˜๊ฐ€ ์—ฌ๋Ÿฌ ๊ฐœ๋ผ๋ฉด ์ข…๋ฅ˜๋ณ„ ์˜ท๊ฐœ์ˆ˜๋ฅผ ๋ชจ๋‘ ๊ณฑํ•ด์„œ ์ตœ์ข… ๊ฒฐ๊ณผ์— ๋”ํ•œ๋‹ค.

์„ฑ๊ณต#

  • ๊ฐ€๋Šฅํ•œ ๋ชจ๋“  ์กฐํ•ฉ์„ ์ง์ ‘ ๊ตฌํ•ด์„œ ๊ณ„์‚ฐํ•˜์ง€ ์•Š์Œ.

  • ์˜์ƒ์˜ ์ข…๋ฅ˜๋ฅผ ์ž…์ง€ ์•Š๋Š” ๊ฒฝ์šฐ๋ฅผ ์ถ”๊ฐ€ํ•ด ๊ณ„์‚ฐ.

  • ์˜ˆ๋ฅผ ๋“ค์–ด ์–ผ๊ตด : 3, ์ƒ์˜ : 2, ํ•˜์˜ : 1 ์ด๋ผ๋ฉด ์ด ๊ฐ€๋Šฅํ•œ ๊ฐœ์ˆ˜๋Š” (3+1) * (2+1) * (1+1) -1 = 13

  • +1์€ ์ฐฉ์šฉํ•˜์ง€ ์•Š์€ ๊ฒฝ์šฐ๊ฐ€ ์ถ”๊ฐ€ ๋˜๊ธฐ ๋•Œ๋ฌธ์ด๊ณ  ๋งˆ์ง€๋ง‰ -1์€ ์˜ท์„ ์ž…์ง€ ์•Š์€ ๊ฒฝ์šฐ๋Š”์—†๊ธฐ ๋•Œ๋ฌธ

์ฝ”๋“œ#

์‹คํŒจ#

function solution(clothes) {    const hashMap = clothes.reduce(        (acc, cur) => acc.set(cur[1], (acc.get(cur[1]) || 0) + 1),        new Map(),    );
    let answer = getAllCombinations([...hashMap.values()]).reduce(        (acc, cur) =>            acc +            cur.reduce((acc, cur, idx) => (idx === 0 ? acc + cur : acc * cur), 0),        0,    );
    return answer;}
const getKCombinations = (set, k) => {    const results = [];    if (k === 1) {        return set.map((i) => [i]);    }
    set.forEach((fixed, i, set) => {        const combinations = getKCombinations(set.slice(i + 1), k - 1);        results.push(...combinations.map((combination) => [fixed, ...combination]));    });
    return results;};
const getAllCombinations = (set) => {    const results = [];    for (let k = 1; k <= set.length; k++) {        const kCombinations = getKCombinations(set, k);        results.push(...kCombinations);    }    return results;};

์„ฑ๊ณต#

const solution = (clothes) =>    Object.values(        clothes.reduce((acc, cur) => {            acc[cur[1]] = (acc[cur[1]] || 1) + 1;            return acc;        }, {}),    ).reduce((acc, cur) => (acc === 0 ? acc + cur : acc * cur), 0) - 1;
module.exports = solution;

์‹œ๊ฐ„ ๋ณต์žก๋„#

์‹คํŒจ#

hashMap ๊ตฌ์„ฑ : O(N), getAllCombinations : O(nC1 + nC2 + nC3 + ... nCn) = O(2^n)

์„ฑ๊ณต#

hashMap ๊ตฌ์„ฑ : O(N), ๋งต ์ˆœํšŒ : O(M), (M < 4)

O(N)+ O(M)

์–ด๋ ค์› ๋˜ ์ #

  • ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค 1์— ๋Œ€ํ•ด ๋Ÿฐํƒ€์ž„ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•˜๋Š”๋ฐ ์•„๋งˆ ์žฌ๊ท€ ํ˜ธ์ถœ๋กœ ์ธํ•œ stack overflow ๋ฌธ์ œ์ธ ๋“ฏํ•˜๋‹ค.

  • ๋ชจ๋“  ์กฐํ•ฉ์„ ๊ตฌํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ๊ตฌํ˜„ํ–ˆ๋Š”๋ฐ, ์กฐํ•ฉ ์•Œ๊ณ ๋ฆฌ์ฆ˜์ด ๊ฝค ์–ด๋ ค์› ๋‹ค.

  • ๊ตณ์ด ์กฐํ•ฉ์„ ๊ตฌํ•˜์ง€ ์•Š์•„๋„ ๋˜๋Š” ์ˆ˜์‹์„ ์ฐพ๋Š” ๊ฒƒ์„ ์ƒ๊ฐ์ง€ ๋ชปํ–ˆ๋‹ค.

์ฐธ๊ณ ์ž๋ฃŒ#