N과 M (1)에서 중복을 제거한 백트래킹이다.
중복을 직접적으로 파악해서 제거하는 대신
중복 숫자가 만들어지지 않도록 코드를 구성했다.
import java.io.*;
import java.util.*;
public class Main {
static int N;
static int M;
static ArrayList<Integer> answer;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] input = br.readLine().split(" ");
N = Integer.parseInt(input[0]);
M = Integer.parseInt(input[1]);
answer = new ArrayList<Integer>();
backTrackingFunction(1, 0);
}
static void backTrackingFunction(int start, int depth){
// start 를 늘려가면서 중복을 건너뛰게 함
// depth 로 자릿수 파악
if(depth == M){
for(int i=0; i<depth; i++){
System.out.print(answer.get(i) + " ");
}
System.out.println();
return;
}
for(int i=start; i<N+1; i++){
answer.add(i);
backTrackingFunction(i + 1, depth + 1);
answer.remove(answer.size() - 1);
}
}
}
'알고리즘 > 백트래킹' 카테고리의 다른 글
[백준 풀이_Java] 15652 N과 M (4) (0) | 2024.02.16 |
---|---|
[백준 풀이_Java] 1182 부분수열의 합 (실버2) (0) | 2024.02.15 |
[백준 풀이_Java] 73447483 로또 (실버2) (0) | 2024.02.15 |
[백준 풀이_Java] 14888 연산자 끼워넣기 (실버1) (0) | 2024.02.08 |
[백준 풀이_Java] 15649 N과 M (1) (실버3) (0) | 2024.02.06 |