백준 15649, N과 M (1)
2021. 9. 22. 13:40ㆍCodingTest
문제
문제요약
1. 1~N까지의 자연수 중에서 M개를 고른 수열을 출력하십시오.
문제풀이
순열을 출력하기 위해서 아래 가지치기와 같은 과정을 수행합니다.
위의 그림과 같이 순열을 생성하는 과정은 재귀적으로 수행되어야 합니다.
소스코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Main {
static int N, M;
static List<Integer> permutation = new ArrayList<Integer>();
static boolean[] chosen;
public static void search()
{
if(permutation.size()==M)
{
permutation.stream().forEach(item -> System.out.print(item + " "));
System.out.println();
}else {
for(int i=1;i<=N; i++)
{
if(chosen[i])
{
continue;
}
chosen[i] = true;
permutation.add(i);
search();
chosen[i] = false;
permutation.remove(permutation.size()-1);
}
}
}
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] str = br.readLine().split(" ");
N = Integer.parseInt(str[0]);
M = Integer.parseInt(str[1]);
chosen = new boolean[N+1];
search();
}
}
References
알고리즘 트레이닝 : 프로그래밍 대회 입문 가이드
'CodingTest' 카테고리의 다른 글
백준 2579, 계단 오르기 (0) | 2021.10.06 |
---|---|
백준 1149, RGB 거리 (0) | 2021.10.05 |
백준 2193, 이천수 (0) | 2021.09.13 |
백준 11653, 소인수분해 (0) | 2021.09.08 |
프로그래머스 위클리 챌린지 6주차 (0) | 2021.09.08 |