https://www.acmicpc.net/problem/15650
15650번: N과 M (2)
한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다. 수열은 사전 순으로 증가하는 순서로 출력해
www.acmicpc.net
중복을 허용하지 않는 조합
nCr
SOLVE
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class n과m1 {
static int N, M;
static int[] result;
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());
result = new int[M];
NCR(0, 0);
}// main end
static void NCR(int sidx, int idx) {
if (sidx == M) {
for (int a : result)
System.out.print(a + " ");
System.out.println();
return;
}
if(idx==N)
return;
result[sidx] = idx + 1;
NCR(sidx + 1, idx + 1);
NCR(sidx, idx + 1);
}// method end
}
Another Solution
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static int N, M;
static int[] result;
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());
result = new int[M];
NCR(1, 0);
}// main end
static void NCR(int idx, int sidx) {
if (sidx == M) {
for (int a : result)
System.out.print(a + " ");
System.out.println();
return;
}
for(int i = idx; i<=N;i++) {
result[sidx] = i;
NCR(i+1, sidx+1);
}
}// method end
}
반응형