자바/알고리즘 문제 풀이

백준/15651 N과 M (3) // 중복 순열

backend dev 2022. 12. 15.

N과 M (3) 성공

 
시간 제한메모리 제한제출정답맞힌 사람정답 비율
1 초 512 MB 46848 31120 23601 66.711%

문제

자연수 N과 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오.

  • 1부터 N까지 자연수 중에서 M개를 고른 수열
  • 같은 수를 여러 번 골라도 된다.

입력

첫째 줄에 자연수 N과 M이 주어진다. (1 ≤ M ≤ N ≤ 7)

출력

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

수열은 사전 순으로 증가하는 순서로 출력해야 한다.

예제 입력 1 복사

3 1

예제 출력 1 복사

1
2
3

예제 입력 2 복사

4 2

예제 출력 2 복사

1 1
1 2
1 3
1 4
2 1
2 2
2 3
2 4
3 1
3 2
3 3
3 4
4 1
4 2
4 3
4 4

풀이

중복순열 문제이다.

import java.io.*;

public class Main {

    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
    /**
     * 중복 순열
     * 중복을 막는 방문배열을 없앤다.
     */

    public static void main(String[] args) throws IOException {
        String[] input = br.readLine().split(" ");
        int n = Integer.parseInt(input[0]);
        int r = Integer.parseInt(input[1]);
        int[] result = new int[r];
        permutation(n, r,  result, 0);
        bw.flush();
        bw.close();

    }

    public static void permutation(int n, int r,int[] result,int count) throws  IOException{
        if (count == r) {
            for (int i = 0; i < r; i++) {
                bw.write(result[i] + " ");
            }
            bw.newLine();
            return;
        }
        for (int i = 0; i < n; i++) {
            result[count] = i + 1; //결과값을 저장할때 인덱스는 지금까지 뽑은갯수여야만 한다.
            permutation(n, r,result,count+1);
        }

    }

}

 

 

 

댓글