728x90
반응형
콤비네이션을 구하는 코드이다.
int[] combi 배열을 만들고,
for문으로 순회하면서 combi 배열을 채우고,
조합해야할 개수의 수만큼 도달했을 때
조합되어지는 수들의 경우를 출력한다.
package _08_dfsBfs._009_getCombi;
/**
*
입력
4 2
출력
1 2
1 3
1 4
2 3
2 4
3 4
*/
import java.util.Scanner;
public class Main {
static int[] combi;
static int n, m;
public static void dfs(int L, int s) {
if(L == m) {
for(int x : combi) System.out.print(x + " ");
System.out.println();
} else {
for (int i = s; i <= n; i++) {
combi[L] = i;
dfs(L+1, i+1);
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
combi = new int[m];
dfs(0, 1);
}
}
1부터 6까지의 수 중, 2개를 뽑는 경우는
6 2
1 2
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
4 5
4 6
5 6
와 같이 결과가 나온다.
728x90
반응형
'알고리즘' 카테고리의 다른 글
[알고리즘/java] 2차원 배열 행, 열, 대각선 최대값 구하기 (0) | 2021.09.06 |
---|---|
[알고리즘/java] 에라스토테네스의 체 - int형 배열 (0) | 2021.09.06 |
[알고리즘/java] 알맞은 팰린드롬(회문) (0) | 2021.09.06 |
[알고리즘/java] 중복된 문자 제거하기 (0) | 2021.09.06 |
[알고리즘/java] 특정 문자만 뒤집기를 할 때 (0) | 2021.09.06 |
댓글