문제

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

  • 1부터 N까지 자연수 중에서 중복 없이 M개를 고른 수열

입력

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

출력

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

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

예제 입력 1

3 1

예제 출력 1

1
2
3

예제 입력 2

4 2

예제 출력 2

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

예제 입력 3

4 4

예제 출력 3

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

더보기

Solution

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>

void N_M(int *A,int N,int M,int current)
{
	if(current==M)
	{
		for(int m=0;m<M;m++)
			printf("%d ", A[m]);
		printf("\n");
	}
	else
		for(int n=1;n<=N;n++)
		{
			bool same=false;

			for(int i=0;i<current;i++)
				if(A[i]==n)
				{
					same=true;
					break;
				}
			if(!same)
			{
				A[current]=n;
				N_M(A,N,M,current+1);
			}
		}
}

int main(void)
{
	int N, M, *A=NULL;

	scanf("%d %d", &N, &M);
	A=(int *)malloc(M*sizeof(int));

	N_M(A,N,M,0);

	free(A);
	return 0;
}
더보기

Solution

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

public class Main {
	public static int N, M;
	public static StringBuilder sb=new StringBuilder();

	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;

		st=new StringTokenizer(br.readLine());
		N=Integer.parseInt(st.nextToken());
		M=Integer.parseInt(st.nextToken());
		int[] A=new int[M];
		
		N_M(A,0);
		
		System.out.println(sb.toString());
	}
	
	public static void N_M(int[] A,int current) {
		if(current==M) {
			for(int m=0;m<M;m++)
				sb.append(A[m]+" ");
			sb.append("\n");
			return;
		}
		
		for(int n=1;n<=N;n++) {
			boolean same=false;
			
			for(int i=0;i<current;i++)
				if(A[i]==n) {
					same=true;
					break;
				}
			
			if(!same) {
				A[current]=n;
				N_M(A,current+1);
			}
		}
	}
}

 

728x90

+ Recent posts