1759번: 암호 만들기
첫째 줄에 두 정수 L, C가 주어진다. (3 ≤ L ≤ C ≤ 15) 다음 줄에는 C개의 문자들이 공백으로 구분되어 주어진다. 주어지는 문자들은 알파벳 소문자이며, 중복되는 것은 없다.
www.acmicpc.net
문제
C 개의 문자들갯수가 주어질 때 주어진 조건에 맞춰서 가능한 L개의 암호를 뽑기 -> 조합
조합의 기본 구조
combination( 어디부터 뽑을지 idx, 몇개 뽑았는지 k, 뽑아서 어디에 저장할건지 sel [ ] )
package algo_prepare_Atest;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class BJ암호만들기 {
static int L,C;
public static void main(String[] args) throws FileNotFoundException {
System.setIn(new FileInputStream("input/암호만들기.txt"));
Scanner sc = new Scanner(System.in);
L = sc.nextInt();
C = sc.nextInt();
char [] words = new char[C];
for (int i = 0; i < C; i++) {
words[i] = sc.next().charAt(0);
}
//System.out.println(Arrays.toString(words));
Arrays.sort(words);
combination(new char[L],0,0,words);
}
private static void combination(char[] sel, int idx, int k, char []words) {
if(k == sel.length) {
int cnt_M=0, cnt_J=0;
for (int i = 0; i < sel.length; i++) {
if(sel[i] == 'a' || sel[i] == 'e'|| sel[i] == 'i'|| sel[i] == 'o'|| sel[i] == 'u') {
cnt_M++;
}else {
cnt_J++;
}
}
if(cnt_M>=1 && cnt_J>=2) {
Arrays.sort(sel);
for (int i = 0; i < sel.length; i++) {
System.out.print(sel[i]);
}
System.out.println();
}
return; //**재귀호출시 return 절대 까먹지 말기
}
for (int i = idx; i < words.length; i++) {
sel[k] = words[i];
combination(sel, i+1, k+1, words);
}
}
}
재귀호출시 return 까먹었더니 ArrayIndexOutofBounds 에러가 났다. 재귀시 리턴 까먹지않게 주의!!!!
'Problem Solving > BOJ' 카테고리의 다른 글
[백준] -3190번 뱀 (0) | 2021.03.16 |
---|---|
[백준] 14888번 연산자 끼워넣기 (0) | 2021.03.14 |
백준- 16506 CPU (0) | 2021.03.07 |
백준- 8911 거북이 (0) | 2021.03.07 |
백준- 13300 방 배정 (0) | 2021.02.22 |
댓글