본문 바로가기

카테고리 없음

[java] 백트래킹으로 부분집합 구하기

import java.io.*;
import java.util.*;

public class Main {
    static int n;
    static int [] arr;
    static int [] nArr;
    static boolean [] visited;

    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        n = Integer.parseInt(st.nextToken());

        arr = new int[n];
        visited = new boolean[n];

        for (int i = 1; i <= n; i++) {
            nArr = new int[i];
            backtracking(0,i,0);
        }
    }
    public static void backtracking(int depth, int len,int p) {
        if (len==depth) {
            for(int i: nArr){
                System.out.print(i+" ");
            }
            System.out.println();
        }
        else{
            for (int i=p; i<n ;i++){
                if(!visited[i]){
                    nArr[depth] = i+1;
                    visited[i] = true;
                    backtracking(depth+1,len,i+1);
                    visited[i] = false;
                }
            }
        }
    }
}​
입력:4 

출력:
1 
2 
3 
4 
1 2 
1 3 
1 4 
2 3 
2 4 
3 4 
1 2 3 
1 2 4 
1 3 4 
2 3 4 
1 2 3 4