[백준][15650번] N과 M(2)
Updated:
문제 URLPermalink
https://www.acmicpc.net/problem/15650
내 풀이Permalink
import java.io.*;
import java.util.StringTokenizer;
public class Main {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
static int[] ans;
public static void main(String[] args) throws IOException {
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
ans = new int[m];
cal(0, 1, n, m);
bw.flush();
bw.close();
}
public static void cal(int idx, int start, int n, int m) throws IOException {
if (idx == m) {
StringBuilder sb = new StringBuilder();
for (int a : ans)
sb.append(a + " ");
bw.write(sb.toString());
bw.newLine();
return;
}
for (int i = start; i <= n; i++) {
ans[idx] = i;
cal(idx + 1, i + 1, n, m);
}
}
}
다른 풀이법 (선택의 관점) **Permalink
import java.util.*;
public class Main {
static int[] a = new int[10];
//index : 자연수, index라는 수를 결과에 포함할껀지 말껀지 결정
//selected 지금까지 선택한 수의 개수
static void go(int index, int selected, int n, int m) {
if (selected == m) {
for (int i=0; i<m; i++) {
System.out.print(a[i]);
if (i != m-1) System.out.print(' ');
}
System.out.println();
return;
}
if (index > n) return;
//index를 추가
//(먼저 나와야함- 숫자 크기 순으로 나와야 하기떄문)
a[selected] = index;
go(index+1, selected+1, n, m);
//index를 추가안함
a[selected] = 0;
go(index+1, selected, n, m);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
go(1, 0, n, m);
}
}
느낀점Permalink
전형적인 브루트포스다.
N과 M(1)처럼 앞에 나왔던 중복제거 코드를 넣을필요없이 오름차순만 신경쓰면된다. 시간복잡도: O(N!)
- 나랑 다른방법 *** 오름차순만 고르는 것이기 때문에 다른방식도 가능하다. 선택의 관점 에서 보자.
각각의 자연수를 선택하는 경우와 선택하지 않는 경우가 있다.
1을 포함될수있고 않을수도 …….N까지 진행
이렇게 결정된 숫자만 모아서 수열을 만들어주면
이게 n까지 자연수중에 중복없이 m개를 고르는것과 같은의미
시간복잡도 : O(2N)
Leave a comment