순열,조합

Updated:


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class GoodDay {
    static char[] src = {'a', 'b', 'c', 'd'};
	static int cnt;
    public static void main(String[] args) {

        // 1. src에서 3개를 뽑아서 만들 수 있는 조합을 모두 출력하시오.
        System.out.println("조합");
         makeCombination(3,new char[3], 0);
        // 2. src에서 3개를 뽑아서 만들 수 있는 순열을 모두 출력하시오.
        System.out.println("순열");
         makePermutation(3, new char[3], new boolean[src.length]);
    }


    static void makeCombination(int toChoose, char [] choosed, int startIdx) {
		if (toChoose == 0) {
			System.out.println(++cnt + " : " + Arrays.toString(choosed));
			return;
		}

		for (int i = startIdx; i < src.length; i++) {
			choosed[choosed.length - toChoose] = src[i];
			makeCombination(toChoose - 1, choosed, i + 1);
		}
    }

    static void makePermutation(int toChoose, char [] choosed, boolean [] visited) {
		if (toChoose == 0) {

			System.out.println(++cnt + " : " + Arrays.toString(choosed));
			return;
		}
		for (int i = 0; i < src.length; i++) {

			if (!visited[i]) {
				visited[i] = true;
				choosed[choosed.length - toChoose] = src[i];
				makePermutation(toChoose - 1, choosed, visited);
				visited[i] = false;
			}
		}
    }
}

Tags: ,

Categories:

Updated:

Leave a comment