yeoseon / tip-archive

트러블 슈팅 및 팁을 모아두는 레포 (Today I Learned)
29 stars 2 forks source link

[알고리즘] 순열, 조합, 중복순열, 중복조합 #250

Open yeoseon opened 3 years ago

yeoseon commented 3 years ago

개요

순열

조합

풀이 1: 백트래킹 이용

https://github.com/yeoseon/tip-archive/issues/251 참고

// 백트래킹 사용
// 사용 예시 : combination(arr, visited, 0, n, r)
static void combination(int[] arr, boolean[] visited, int start, int n, int r) {
    if(r == 0) {
        print(arr, visited, n);
        return;
    } 

    for(int i=start; i<n; i++) {
        visited[i] = true;
        combination(arr, visited, i + 1, n, r - 1);
        visited[i] = false;
    }
}

풀이 2: 재귀 이용

// 재귀 사용
// 사용 예시 : comb(arr, visited, 0, n, r)
static void comb(int[] arr, boolean[] visited, int depth, int n, int r) {
    if (r == 0) {
        print(arr, visited, n);
        return;
    }

    if (depth == n) {
        return;
    }

    visited[depth] = true;
    comb(arr, visited, depth + 1, n, r - 1);

    visited[depth] = false;
    comb(arr, visited, depth + 1, n, r);
}

Reference