Search
Duplicate
📒

[Programmers] 01-2. 의상

상태
완료
수업
Algorithm Solving
주제
Programmers
4 more properties
참고

문제해설

NOTE
입력 값 ⇒ 2차원 문자열 배열(가지고 있는 옷)
출력 값 ⇒ 2차원 문자열 배열에서 나올 수 있는 의상의 조합의 수

문제 로직고민

NOTE
각 의상의 종류의 개수를 모두구하고 모두 곱하면 조합의 수가 나온다.
단 착용하지 않는 경우도 존재하므로 의상의 개수 + 1로 계산해주어야 한다.
착용하지 않는 경우가 추가되었으므로 모두 착용하지 않는 경우가 포함된다. 이를 위해 결과값은 -1을 해준다.

작성코드

NOTE
class Solution { public int solution(String[][] clothes) { Map<String, Integer> map = new HashMap(); for(String[] s : clothes){ if(map.containsKey(s[1])) map.put(s[1], map.get(s[1]) + 1); else map.put(s[1], 2); } int answer = 1; for(Map.Entry<String, Integer> entry : map.entrySet()){ answer *= entry.getValue(); } return answer-1; } }
Java
복사

다른사람 풀이

NOTE
class Solution { public int solution(String[][] clothes) { return Arrays.stream(clothes) .collect(groupingBy(p -> p[1], mapping(p -> p[0], counting()))) .values() .stream() .collect(reducing(1L, (x, y) -> x * (y + 1))).intValue() - 1; } }
Java
복사
스트림을 사용한 코드
인상깊긴한데 실전에서 쓰기에는 힘들것같다.
class Solution { public int solution(String[][] clothes) { var map = new HashMap<String, Integer>(); for (String[] strings : clothes) { int p = 0; String key = strings[1]; if(map.containsKey(key)){ p = map.get(key); } map.put(key, p+1); } Collection<Integer> values = map.values(); Integer[] counts = new Integer[values.size()]; values.toArray(counts); int[][] dp = new int[values.size()][2]; dp[0][0] = 1; dp[0][1] = counts[0]; for (int i = 1; i < dp.length; i++) { dp[i][0] = dp[i-1][0] + dp[i-1][1]; dp[i][1] = dp[i-1][0] * counts[i] + dp[i-1][1] * counts[i]; } return dp[dp.length-1][0] + dp[dp.length-1][1] -1; } }
Java
복사
dp를 사용한 코드
dp[i][0]: 'i번째 옷은 안 입으면서 1~i-1번째 옷을 조합하는 경우의 수'
dp[i][1]: 'i번째 옷을 입으면서 1~i-1번째 옷을 조합하는 경우의 수’