알고리즘 문제

[BackTracking] boj15656 java "N과 M(7)" - 실버3

민돌v 2021. 7. 19. 23:17
728x90

N과 M (7) 성공

 

시간 제한메모리 제한제출정답맞은 사람정답 비율
1 초 512 MB 7908 6165 4974 79.141%

문제

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

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

입력

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

둘째 줄에 N개의 수가 주어진다. 입력으로 주어지는 수는 10,000보다 작거나 같은 자연수이다.

출력

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

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

package BackTracking;

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

public class boj15656_N과M7 {
	static boolean visit[];
	static int list[];
	static StringBuilder sb = new StringBuilder();

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String temp[] = br.readLine().split(" ");

		int n = Integer.parseInt(temp[0]);
		int m = Integer.parseInt(temp[1]);
		list = new int[n];

		temp = br.readLine().split(" ");

		for (int i = 0; i < n; i++)
			list[i] = Integer.parseInt(temp[i]);

		Arrays.sort(list);
		visit = new boolean[n];

		Permutation(n, m, new int[m], 0, 0);
		System.out.println(sb.toString());
	}

	public static void Permutation(int n, int m, int result[], int count, int start) {
		if (count == m) {
			for (int a = 0; a < m - 1; a++)
				sb.append(result[a] + " ");
			sb.append(result[m - 1] + "\n");

			return;
		}

		for (int i = 0; i < n; i++) {

			result[count] = list[i];
			Permutation(n, m, result, count + 1, i);

		}
	}
}
반응형