https://www.acmicpc.net/problem/15655
15655번: N과 M (6)
N개의 자연수와 자연수 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오. N개의 자연수는 모두 다른 수이다. N개의 자연수 중에서 M개를 고른 수열
www.acmicpc.net
코드설명
백트래킹(BackTracking)을 활용하는 문제입니다.
simulate 메서드 : 해당 함수는 현재까지 선택된 원소의 개수(level)와 다음에 선택할 원소의 인덱스(idx)를 인자로 받습니다.
이를 통해서 중복된 순열을 제거하고 출력할 수 있습니다.
코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
public static int N, M, K;
public static int[] arr;
public static int[] selected;
public static boolean[] visited;
public static int answer = 0;
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
arr = new int[N];
selected = new int[M];
visited = new boolean[N];
for(int i=0;i<N;i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
Arrays.sort(arr);
simulate(0, 0);
}
public static void simulate(int level, int idx) {
if(level == M) {
for(int i=0;i<M;i++) {
System.out.print(selected[i]+" ");
}
System.out.println();
return ;
}
for(int i=idx;i<N;i++) {
if(visited[i] == false) {
visited[i] = true;
selected[level] = arr[i];
simulate(level + 1, i+1);
visited[i] = false;
}
}
}
}
'알고리즘 > 백준' 카테고리의 다른 글
[백준] 16986 인싸들의 가위바위보 - Simulation(시뮬레이션) + Normal Permutation (일반순열) JAVA (0) | 2023.12.20 |
---|---|
[백준] 11559 Puyo Puyo - Simulation(시뮬레이션) + BFS(너비우선탐색) JAVA (0) | 2023.12.20 |
[백준] 4883 삼각 그래프 - 동적계획법(DP, Dynamic Programming) JAVA (0) | 2023.12.18 |
[백준] 11967 불켜기 - BFS(너비우선탐색) JAVA (0) | 2023.12.17 |
[백준] 16920 확장 게임 - BFS(너비우선탐색) JAVA (0) | 2023.12.17 |