메뉴 리뉴얼

LJM·2023년 8월 24일
0

programmers

목록 보기
78/92

https://school.programmers.co.kr/learn/courses/30/lessons/72411

손님이 주문한 단품메뉴들을 완탐으로 중복된 원소가 가지지 않게 탐색해서 가능한 조합을 전부 만들었다.HashSet에 저장
HashSet -> HashMap 조합별로 개수를 저장

조합개수에 맞춰서 가장 많이 주문된것들(중복있으면 둘다 저장)을
ArrayList에 담았다. ArrayList를 정렬하였다. String[] 배열로 변환해서 반환하였다.

import java.util.*;

class Solution {
    public String[] solution(String[] orders, int[] course) {
       
        HashMap<String, Integer> map = new HashMap<>();
        
        for(int i = 0; i < orders.length; ++i)
        {
            char[] charr= orders[i].toCharArray();
            Arrays.sort(charr);
            HashSet<String> set = new HashSet<>();
            
            addMenu(set, charr);
            
            for(String val : set)
            {
                map.put(val, map.getOrDefault(val, 0)+1);
                //System.out.println(val);
            }
        }
        
        ArrayList<String> arranswer = new ArrayList<>();
        for(int i = 0; i < course.length; ++i)
        {
            Set<String> keys = map.keySet();
            int max = 0;
            //String maxStr = "";
            for(String key : keys)
            {
                int curcnt = map.get(key);
                if(key.length() == course[i] && curcnt >= 2)
                {
                    if(max < curcnt)
                    {
                        //maxStr = key;
                        max = curcnt;
                    }
                }
            }
            //System.out.println(max);
            for(String key : keys)
            {
                int curcnt = map.get(key);
                if(key.length() == course[i] && curcnt == max)
                    arranswer.add(key);
            }
            //answer[i] = maxStr;
        }
        
        Collections.sort(arranswer);
         String[] answer = arranswer.toArray(new String[0]);
        
        return answer;
    }
    
    public void addMenu(HashSet<String> set, char[] charr)
    {
        boolean[] visit = new boolean[charr.length];
        char[] arr = new char[charr.length];
        
        dfs(0, 0, visit, set, charr, arr);
    }
    
    public void dfs(int depth, int pre, boolean[] visit, HashSet<String> set, char[] charr, char[] arr)
    {
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < depth; ++i)
        {
            sb.append(arr[i]);
        }
        set.add(sb.toString());
        //System.out.println(sb);
        
        if(depth == visit.length)
            return;
        
        for(int i = pre; i < charr.length; ++i)
        {
            if(visit[i])
                continue;
            visit[i] = true;
            arr[depth] = charr[i];
            dfs(depth+1, i, visit, set, charr, arr);
            visit[i] = false;
        }
    }
}
profile
게임개발자 백엔드개발자

0개의 댓글