[Java] 중복 순열

해질녘·2022년 12월 16일
1

Java

목록 보기
1/2

Python의 combinations 라이브러리에 해당하는 것을 직접 구현하였다. 단순 출력이 아니라 해당 결과를 써먹을 수 있도록 1차원 배열의 vector 전역변수로 저장하였다.

  • arr에서 k개의 원소를 중복순열로 뽑는 방법의 구현이다.

  • 결과 저장 시에 clone을 사용하지 않으면 out값의 주소가 저장된다. clone을 붙여준다.

결과

코드 전문

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Vector;

public class Solve {

    static int K;
    static List<int[]> list = new Vector<>();

    private static void permutation_with_repetition(int[] arr, int[] out, int depth, int k) {
        if (depth == k) {
            System.out.println("out = " + out);
            list.add(out.clone());
            return;
        }
        for (int i = 0; i < arr.length; i++) {
            out[depth] = arr[i];
            permutation_with_repetition(arr, out, depth+1, k);
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        K = Integer.parseInt(st.nextToken());
        int[] arr = {1, 2, 3, 4, 5};

        permutation_with_repetition(arr, new int[K], 0, 3);
        for (int[] o : list) {
            for (int a : o) {
                System.out.print(a + " ");
            }
            System.out.print("\n");
        }

    }
}

0개의 댓글