반응형
문제
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
풀이
첫 번째 풀이 (실패)
각 행은 [의상의 이름, 의상의 종류] 로 이뤄져 있으므로
‘의상의 종류’에 따른 개수를 객체로 묶는다.
서로 다른 옷의 조합의 수를 구해야하는데,
객체가 {A: a, B: b} 라면 총 조합의 수는 a + b + a*b 다.
그래서 total이라는 변수를 두고 구했음.
function solution(clothes) {
const table = {};
for(let i = 0; i < clothes.length; i++) {
table[clothes[i][1]] = (table[clothes[i][1]] ? table[clothes[i][1]] : 0) + 1;
}
if(Object.values(table).length === 1) return Object.values(table)[0]
let answer = 0;
let total = 1;
for(i of Object.values(table)){
answer += i;
total *= i;
}
return answer + total;
}
catastrophie…
두 번째 풀이
바보같이 잘못 접근했음(…)
객체가 {A: a, B:b, C: c} 로 주어졌다면
조합의 수 = a + b + c + AB + BC + CA + AB*C 가 된다.
따라서 경우가 많아질 수록 모든 경우를 생각해야한다는 것.
위에서 통과된 경우들은 모두 2가지 이하의 경우인 듯함.
암튼 모든 경우의 수를 하려면
(n+1)C1한 값을 각 곱하고, 그 값에서 -1을 하면 된다.
-> 안입는 경우의 수까지 더해서 (+1)한 후, 모두 안 입는 경우를 마지막에 뺀 것(-1).
function solution(clothes) {
const hash = {};
for(let i = 0; i < clothes.length; i++) {
hash[clothes[i][1]] = (hash[clothes[i][1]] ? hash[clothes[i][1]] : 0) + 1;
}
const arr = [...Object.values(hash)];
if(arr.length === 1) return arr[0];
let answer = 1;
for(let i = 0; i < arr.length; i++) {
answer *= (arr[i] + 1)
}
return answer - 1;
}
다른 풀이
function solution(clothes) {
let answer = 1;
const obj = {};
for(let arr of clothes) {
obj[arr[1]] = (obj[arr[1]] || 0) + 1;
}
for(let key **in obj**) {
answer *= **(obj[key]+1);**
}
return answer - 1;
}
ㄷㅓ 깔끔함.
반응형
'CS > 알고리즘' 카테고리의 다른 글
[230421] 모의고사 (0) | 2023.04.21 |
---|---|
[230421] n^2 배열 자르기 (0) | 2023.04.21 |
[230420] 캐시 (0) | 2023.04.20 |
[230419] 괄호 회전하기 (0) | 2023.04.19 |
[230419] 멀리 뛰기 (0) | 2023.04.19 |