[Algorithm] N개의 원소중 M개를 골라라

최지영·2022년 9월 6일
0

😁 무식하게 N개의 원소중 M개를 고르는 모든 조합 방법 (재귀함수)

public class RecourSive {

    public static void main(String[] args) {
        Vector<Integer> dataSet = new Vector<>();
        choiceNumber(6,dataSet,3);
    }

    public static void choiceNumber(int n,Vector<Integer> dataSet,int choice){
        // 기저 사례 -> 더 이상 고를 원소가 없을때
        if(choice ==0) {
            dataSet.forEach(System.out::print);
            System.out.println();
        };

        //고를 수 있는 가장 작은 번호
        int smallest = dataSet.isEmpty() ? 0 : dataSet.get(dataSet.size()-1)+1;

        for(int next = smallest; next < n; ++next){
            dataSet.add(next); //넣어보고
            choiceNumber(n,dataSet,choice-1); // 선택할 갯수가 한개씩 줄이는 경우의 수를 만들고
            dataSet.remove(dataSet.size() - 1); // 제거
        }
    };
}

출력 결과


012
013
014
015
023
024
025
034
035
045
123
124
125
134
135
145
234
235
245
345

Process finished with exit code 0

0개의 댓글