조합 - 백준1759 암호 만들기

이형석·2024년 8월 6일

알고리즘 Phase1

목록 보기
58/59

조합의 살짝 응용문제이다.
현재까지 데브코스를 진행하며 배운 순조부 알고리즘 지식 + stream API 를 이용하여 혼자서 풀게 된 문제인데 기념으로 작성ㅎ

import java.util.*;
import java.io.*;
public class Main{
    static int L;
    static int C;
    static String[] arr;
    static String[] aeiou = {"a", "e", "i", "o", "u"};
    static String[] coded;
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        L = Integer.parseInt(st.nextToken());
        coded = new String[L];
        C = Integer.parseInt(st.nextToken());
        arr = new String[C];
        st = new StringTokenizer(br.readLine());
        for(int i = 0; i < C; i++){
            arr[i] = st.nextToken();
        }
        //문제
        //암호 : 최소 1개의 모음 + 최소 2개의 자음 _정렬됨
        //C개 중 L개 뽑기
        //풀이
        //(조합)
        //1. 정렬
        //2. 현재까지 뽑은 모음 수 >= 1 && 뽑은 자음 수 >= 2 && 뽑은 갯수 = 4 이면 출력
        //3. 뽑은 갯수 = 4 이면 리턴
        //4. idx = C이면 리턴
        Arrays.sort(arr);
        dfs(0, 0, 0);
    }
    static void dfs(int idx, int mo, int ja){
        if(mo+ja == L){
            if(mo >= 1 && ja >= 2){
                StringBuilder sb = new StringBuilder();
                Arrays.stream(coded).forEach(s -> sb.append(s));
                System.out.println(sb);
            }
            return;
        }
        if(idx == C){
            return;
        }
        String nowChar = arr[idx];
        int nextMo = mo;
        int nextJa = ja;
        boolean isMo = Arrays.stream(aeiou).anyMatch(s -> s.equals(nowChar));
        if(isMo){
            nextMo++;
        }else{
            nextJa++;
        }
        //현재 포함하고 idx++
        coded[nextMo+nextJa-1] = arr[idx];
        dfs(idx+1, nextMo, nextJa);
        //현재 포함하지 않고 idx++
        dfs(idx+1, mo, ja);
    }
}
profile
금융IT 개발자

0개의 댓글