데이터 엔지니어링 정복/Algorithm
[브루트포스&백트래킹] 백준 - N과 M (8)
eeaarrtthh
2021. 9. 1. 12:00
728x90
반응형
https://www.acmicpc.net/problem/15657
-문제해설
갑자기 해설쓰는게 귀찮다....
미래의 내가 안틀리고 잘 풀 수 있겠지...?
미래의 나 파이팅~
-자바
package bruteforce;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class BJ15657 {
static int n, m;
static int[] arr, ans;
static StringBuilder sb = new StringBuilder();
public static void dfs( int start, int depth ) {
if( depth == m ) {
for( int val : ans ) sb.append( val ).append( " " );
sb.append( "\n" );
return;
}
for( int i=start; i<n; i++ ) {
ans[depth] = arr[i];
dfs( i, depth+1 );
}
}
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() );
arr = new int[n];
ans = new int[m];
st = new StringTokenizer( br.readLine() );
for( int i=0; i<n; i++ ) arr[i] = Integer.parseInt( st.nextToken() );
Arrays.sort( arr );
dfs( 0, 0 );
System.out.println( sb );
}
}
-파이썬
from sys import stdin
def dfs( start, depth ):
global n, m, arr, ans
if depth == m:
print( ' '.join( map(str, ans) ) )
return
for i in range( start, n ):
ans[depth] = arr[i]
dfs( i, depth+1 )
input = stdin.readline
n, m = map(int, input().split())
arr = list( map(int, input().split()) )
ans = [0] * m
arr.sort()
dfs( 0, 0 )
728x90
반응형