백준/백트래킹

BOJ 15651 - N과 M(3)

누누01 2022. 11. 15. 12:09
728x90

https://www.acmicpc.net/problem/15651

 

15651번: N과 M (3)

한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다. 수열은 사전 순으로 증가하는 순서로 출력해

www.acmicpc.net

 


이번 문제는 중복을 허용하는 문제이다.

N과 M 시리즈에서 우리는 중복을 허용하지 않기 위해 boolean[] 타입 VISITED를 사용하였으니, 이것을 삭제하면 쉽게 해결할 수 있다.

 

코드는 다음과 같다.

 

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {
    static int NUMBER;
    static int LENGTH;
    static int[] ARR;
    static StringBuilder SB = new StringBuilder();

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        NUMBER = Integer.parseInt(st.nextToken());
        LENGTH = Integer.parseInt(st.nextToken());
        ARR = new int[LENGTH];

        dfs(0);

        System.out.println(SB);
        br.close();
    }

    public static void dfs(int depth) {
        if (depth == LENGTH) {
            for (int i = 0; i < ARR.length; i++) {
                SB.append(ARR[i] + " ");
            }
            SB.append("\n");

            return;
        }

        for (int i = 1; i <= NUMBER; i++) {
            ARR[depth] = i;
            dfs(depth + 1);
        }
    }
}