개발일지/Algorithm

백준 - 15656 N과 M (7) [백트래킹]

E-room 2023. 9. 28. 19:03
728x90

 

 

15656번: N과 M (7)

N개의 자연수와 자연수 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오. N개의 자연수는 모두 다른 수이다. N개의 자연수 중에서 M개를 고른 수열

www.acmicpc.net

 

1. 문제 요약

주어진 숫자들 중 M개를 골라 오름차순으로 정렬된 수열을 생성하라.

같은 수를 여러 번 사용해도 된다.

 

2. 접근 방법

  • 입력받은 숫자들을 오름차순 정렬
  • 재귀함수를 이용하여 수열 생성

 

3. 파이썬

from sys import stdin
input = stdin.readline

def solution(depth: int):
    if depth == M:
        print(' '.join(map(str, arr)))
        return

    for i in range(N):
        arr[depth] = nums[i]
        solution(depth + 1)

N, M = map(int, input().split())
nums = list(map(int, input().split()))
nums.sort()
arr = [0] * M

solution(0)

 

4. 자바

static int N, M;
static int[] nums;
static int[] arr;
static StringBuilder sb = new StringBuilder();

static void solution(int depth) {
    if (depth == M) {
        for (int i : arr) {
            sb.append(i).append(' ');
        }
        sb.append('\n');
        return;
    }

    for (int i = 0; i < N; i++) {
        arr[depth] = nums[i];
        solution(depth + 1);
    }
}

 

5. 전체 코드

https://github.com/Ksiyeong/Algorithm/tree/main/%EB%B0%B1%EC%A4%80/Silver/15656.%E2%80%85N%EA%B3%BC%E2%80%85M%E2%80%85%EF%BC%887%EF%BC%89

728x90