백준 - 15656 - N과 M(7)

2021. 3. 9. 14:15Algorithm

www.acmicpc.net/problem/15656

 

15656번: N과 M (7)

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

www.acmicpc.net

import java.util.Arrays;
import java.util.Scanner;

/**
 * 백준 15656
 * 순열
 */
public class N과_M_7 {
    private static int N;
    private static StringBuilder sb = new StringBuilder();
    private static int[] array;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String[] inputs = sc.nextLine().split(" ");
        N = Integer.parseInt(inputs[0]);
        int M = Integer.parseInt(inputs[1]);
        array = new int[N+1];
        String[] nums = sc.nextLine().split(" ");
        for(int i=1; i<=N; i++) {
            array[i] = Integer.parseInt(nums[i-1]);
        }
        Arrays.sort(array);
        printPermutation(M, "");
        System.out.println(sb);
    }

    private static void printPermutation(int M, String str) {
        if(M == 0) {
            sb.append(str.trim() + "\n");
            return;
        }

        for(int i=1; i<array.length; i++) {
            printPermutation(M - 1, str + " " + array[i]);
        }
    }
}

문제

주어진 배열에서 중복 요소가 있는 순열

 

알고리즘

  • 백트래킹, 순열

'Algorithm' 카테고리의 다른 글

백준 - 15663 - N과 M(9)  (0) 2021.03.09
백준 - 15657 - N과 M(8)  (0) 2021.03.09
백준 - 15655 - N과 M(6)  (0) 2021.03.09
백준 - 15654 - N과 M(5)  (0) 2021.03.09
백준 - 15652 - N과 M(4)  (0) 2021.03.09