728x90
반응형
https://programmers.co.kr/learn/courses/30/lessons/42578
1번풀이
#include <string>
#include <vector>
#include <iostream>
#include <map>
using namespace std;
int solution(vector<vector<string>> clothes) {
map<string, int> m;
int ans = 1;
for (int i = 0; i < clothes.size(); ++i)
{
m[clothes[i][1]]++;
cout<<"clothes["<<i<<"][1] = "<<clothes[i][1]<<endl;
cout<<"m[clothes["<<i<<"][1]] = "<<m[clothes[i][1]]<<endl;
}
for (auto it = m.begin(); it != m.end(); ++it)
{
ans *= (it->second) + 1;
cout<<"it->first = "<<it->first<<endl;
cout<<"it->second = "<<it->second<<endl;
}
return ans - 1;
}
int main() {
vector<vector<string>> c = { {"yellow_hat", "headgear"},
{"blue_sunglasses", "eyewear" }, { "green_turban", "headgear" }};
cout << solution(c) << "\n";
return 0;
}
콘솔 창의 결과 :
clothes[0][1] = headgear m[clothes[0][1]] = 1 clothes[1][1] = eyewear m[clothes[1][1]] = 1 clothes[2][1] = headgear m[clothes[2][1]] = 2 it->first = eyewear it->second = 1 it->first = headgear it->second = 2 5 |
1. map<string, int> m 을 선언
2. vector<vector<string>> clothes 의 크기 만큼 반복
2-1. clothes[0][1] 에 headgear가 담김
2-2. m[headgear] = 1 이 됨
2-3. clothes[1][1] 에 eyewear가 담김
2-4. m[eyewear] = 1이 됨
2-5. clothes[2][1] 에 headgear가 담김
2-6. m[headgear] = 2가 됨
3. map<string, int> m 의 크기만큼 반복
3-1. it->first = eyewear (왜 eyewear 가 먼저 나오는지 모르겠음)
it->second = 1
3-2. it->first = headgear
it->second = 2
4. 경우의 수 (1+1) * (2+1) - 1 = 5 가 답!
2번 풀이
#include <string>
#include <vector>
#include <map>
using namespace std;
int solution(vector<vector<string>> clothes) {
map<string, int> m;
for(vector<string> c : clothes){
m[c[1]]++;
cout<<"c[0] = "<<c[0]<<endl;
cout<<"c[1] = "<<c[1]<<endl;
cout<<"m["<<c[1]<<"] = "<<m[c[1]]<<endl;
}
int answer = 1;
map<string, int>::iterator it;
for(it=m.begin(); it!=m.end(); it++){
answer *= it->second+1;
}
return answer-1;
}
콘솔 창의 결과 :
c[0] = yellow_hat c[1] = headgear m[headgear] = 1 c[0] = blue_sunglasses c[1] = eyewear m[eyewear] = 1 c[0] = green_turban c[1] = headgear m[headgear] = 2 |
3번 풀이
#include <string>
#include <vector>
#include <unordered_map>
using namespace std;
int solution(vector<vector<string>> clothes) {
unordered_map <string, int> myclothes;
int answer = 1;
for(auto item : clothes)
myclothes[item[1]]++;
for(auto tmp : myclothes)
answer *= (tmp.second+1);
return answer-1;
}
그리고 javascript 버전
function solution(clothes) {
var answer = 1;
let map = new Map();
for(let i=0; i<clothes.length; i++){
const type = clothes[i][1];
let value = map.get(type);
if(!value) map.set(type, 1);
else map.set(type, ++value);
}
for (let [key, value] of map) {
answer *= (value+1);
}
return --answer;
}
열심히하자!
728x90
반응형
'알고리즘' 카테고리의 다른 글
[재귀함수] 미로찾기 (0) | 2021.11.29 |
---|---|
[프로그래머스/JAVA] 프린터 (0) | 2021.11.16 |
[프로그래머스/C++] 베스트앨범 (0) | 2021.10.13 |
[C++] vector, map (0) | 2021.10.06 |
[프로그래머스/C++] 전화번호 목록 (0) | 2021.10.05 |