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. 전체 코드
728x90
'개발일지 > Algorithm' 카테고리의 다른 글
백준 - 19942 다이어트 [백트래킹] (1) | 2023.10.06 |
---|---|
백준 - 2961 도영이가 만든 맛있는 음식 [백트래킹] (0) | 2023.10.06 |
백준 - 15650 N과 M (6) [조합] (0) | 2023.09.28 |
백준 - 15654 N과 M (5) [순열] (0) | 2023.09.28 |
백준 - 15652 N과 M (4) [백트래킹] (2) | 2023.09.28 |
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. 전체 코드
728x90
'개발일지 > Algorithm' 카테고리의 다른 글
백준 - 19942 다이어트 [백트래킹] (1) | 2023.10.06 |
---|---|
백준 - 2961 도영이가 만든 맛있는 음식 [백트래킹] (0) | 2023.10.06 |
백준 - 15650 N과 M (6) [조합] (0) | 2023.09.28 |
백준 - 15654 N과 M (5) [순열] (0) | 2023.09.28 |
백준 - 15652 N과 M (4) [백트래킹] (2) | 2023.09.28 |