mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-27 23:11:57 +08:00
Release reviewed gh-pages candidate
This commit is contained in:
@@ -2047,8 +2047,8 @@
|
||||
<p>백트래킹 관점에서는 <strong>순열을 만드는 과정을 연속된 선택의 결과로 볼 수 있다</strong>. 입력 배열이 <span class="arithmatex">\([1, 2, 3]\)</span>이고 <span class="arithmatex">\(1\)</span>, <span class="arithmatex">\(3\)</span>, <span class="arithmatex">\(2\)</span> 순서로 선택하면 순열 <span class="arithmatex">\([1, 3, 2]\)</span>를 얻는다. 되돌리기는 선택 하나를 취소한 뒤 다른 선택을 계속 시도한다는 뜻이다.</p>
|
||||
<p>백트래킹 코드에서 후보 집합 <code>choices</code>는 입력 배열의 모든 원소이고, 상태 <code>state</code>는 지금까지 선택한 원소들이다. 각 원소는 한 번만 선택할 수 있으므로 <strong><code>state</code> 안의 원소는 모두 중복되지 않아야 한다</strong>.</p>
|
||||
<p>아래 그림(13-5)과 같이 탐색 과정을 재귀 트리로 펼칠 수 있다. 각 노드는 현재 상태 <code>state</code>를 나타낸다. 루트에서 시작해 세 차례 선택하면 리프에 도달하며, 각 리프 노드는 순열 하나에 대응한다.</p>
|
||||
<p><ha-svg-figure class="animation-figure" data-book-key="ko/chapter_backtracking/permutations_problem.assets/permutations_i.png" data-dark-src="/assets/figure-svg/figures/3cb2af9c6f6195acd4dc7d19.json" data-src="/assets/figure-svg/figures/88b8811dd2daec741f77d887.json" style=";--figure-ratio:960.0/540.0"><object data="/ko/chapter_backtracking/permutations_problem.assets/permutations_i.svg" data-theme="light" tabindex="-1" type="image/svg+xml">모든 순열의 재귀 트리</object><object data="/ko/chapter_backtracking/permutations_problem.assets/permutations_i.dark.svg" data-theme="dark" tabindex="-1" type="image/svg+xml">모든 순열의 재귀 트리</object></ha-svg-figure></p>
|
||||
<p align="center"> 그림 13-5 모든 순열의 재귀 트리 </p>
|
||||
<p><ha-svg-figure aria-label="중복 원소가 없는 모든 순열의 재귀 선택 트리" class="animation-figure" data-book-key="ko/chapter_backtracking/permutations_problem.assets/permutations_i.png" data-dark-src="/assets/figure-svg/figures/3cb2af9c6f6195acd4dc7d19.json" data-figure-accessible="" data-src="/assets/figure-svg/figures/88b8811dd2daec741f77d887.json" role="img" style=";--figure-ratio:960.0/540.0"><object aria-hidden="true" data="/ko/chapter_backtracking/permutations_problem.assets/permutations_i.svg" data-theme="light" inert="" tabindex="-1" type="image/svg+xml">모든 순열의 재귀 트리</object><object aria-hidden="true" data="/ko/chapter_backtracking/permutations_problem.assets/permutations_i.dark.svg" data-theme="dark" inert="" tabindex="-1" type="image/svg+xml">모든 순열의 재귀 트리</object></ha-svg-figure></p>
|
||||
<p align="center"> 그림 13-5 모든 순열의 재귀 트리 </p><div class="ha-sr-only figure-description"><h3>그림 13-5 설명: 중복 원소가 없는 모든 순열의 재귀 선택 트리</h3><p>빈 접두 수열에서 출발해 매 차례 [1, 2, 3] 중 아직 사용하지 않은 원소 하나를 골라 state에 추가하며 세 차례에 걸쳐 6개의 순열을 생성한다.</p><p>입력 후보 배열은 choices = [1, 2, 3]으로 세 원소가 서로 다르며, 한 순열 안에서 각 원소는 한 번만 사용할 수 있다. 루트 노드는 비어 있는 세 슬롯으로 그려져 아직 어떤 원소도 채우지 않은 빈 접두 수열 []를 나타내며, 빈 슬롯 자체는 원소 값이 아니다.</p><p>그림은 모든 재귀 가지를 동시에 펼쳐 놓았지만, 실제 백트래킹 코드는 리프 노드에서 state를 복사해 저장한 뒤 마지막 원소를 꺼내고 그 원소를 미선택 상태로 되돌려 형제 가지를 시도한다.</p><p>선택 트리는 0층의 빈 접두 수열부터 3층의 리프 노드까지 총 네 층으로 이루어진다. 아래 두 표는 각각 접두 수열별 후속 선택과 순번별 전체 여섯 순열을 보여 준다.</p><table><caption>접두 수열별 후속 선택 조회</caption><thead><tr><th scope="col">현재 접두 수열</th><th scope="col">선택 가능한 원소</th><th scope="col">다음 층 접두 수열 또는 리프 결과</th></tr></thead><tbody><tr><th scope="row">[]</th><td>1, 2, 3</td><td>[1]; [2]; [3]</td></tr><tr><th scope="row">[1]</th><td>2, 3</td><td>[1, 2]; [1, 3]</td></tr><tr><th scope="row">[2]</th><td>1, 3</td><td>[2, 1]; [2, 3]</td></tr><tr><th scope="row">[3]</th><td>1, 2</td><td>[3, 1]; [3, 2]</td></tr><tr><th scope="row">[1, 2]</th><td>3</td><td>[1, 2, 3]</td></tr><tr><th scope="row">[1, 3]</th><td>2</td><td>[1, 3, 2]</td></tr><tr><th scope="row">[2, 1]</th><td>3</td><td>[2, 1, 3]</td></tr><tr><th scope="row">[2, 3]</th><td>1</td><td>[2, 3, 1]</td></tr><tr><th scope="row">[3, 1]</th><td>2</td><td>[3, 1, 2]</td></tr><tr><th scope="row">[3, 2]</th><td>1</td><td>[3, 2, 1]</td></tr></tbody></table><table><caption>전체 여섯 순열</caption><thead><tr><th scope="col">결과 순번</th><th scope="col">완성된 순열</th></tr></thead><tbody><tr><th scope="row">1</th><td>[1, 2, 3]</td></tr><tr><th scope="row">2</th><td>[1, 3, 2]</td></tr><tr><th scope="row">3</th><td>[2, 1, 3]</td></tr><tr><th scope="row">4</th><td>[2, 3, 1]</td></tr><tr><th scope="row">5</th><td>[3, 1, 2]</td></tr><tr><th scope="row">6</th><td>[3, 2, 1]</td></tr></tbody></table><p>첫 번째, 두 번째, 세 번째 선택 차례에서 각 노드가 고를 수 있는 원소 수는 차례로 3, 2, 1개이므로 총 3 × 2 × 1 = 6개의 리프 노드가 생성되며, 이는 [1, 2, 3]의 가능한 모든 순열 6개에 대응한다.</p></div>
|
||||
<h3 id="1">1. 중복 선택 가지치기<a class="headerlink" href="#1" title="고유 링크">¶</a></h3>
|
||||
<p>각 원소를 한 번만 선택하도록 불리언 배열 <code>selected</code>를 도입하자. <code>selected[i]</code>는 <code>choices[i]</code>를 이미 선택했는지 나타내며, 이를 바탕으로 다음과 같이 가지치기한다.</p>
|
||||
<ul>
|
||||
@@ -2056,8 +2056,8 @@
|
||||
<li>선택지 리스트 <code>choices</code>를 순회할 때 이미 선택한 모든 노드를 건너뛰어 가지치기한다.</li>
|
||||
</ul>
|
||||
<p>아래 그림(13-6)처럼 첫 번째에 1, 두 번째에 3, 세 번째에 2를 선택한다면, 두 번째에서는 원소 1의 가지를, 세 번째에서는 원소 1과 3의 가지를 잘라 내야 한다.</p>
|
||||
<p><ha-svg-figure class="animation-figure" data-book-key="ko/chapter_backtracking/permutations_problem.assets/permutations_i_pruning.png" data-dark-src="/assets/figure-svg/figures/f1fc5c4d6c71591f87e4a21a.json" data-src="/assets/figure-svg/figures/7fba710b58ba02f07fe63356.json" style=";--figure-ratio:960.0/540.0"><object data="/ko/chapter_backtracking/permutations_problem.assets/permutations_i_pruning.svg" data-theme="light" tabindex="-1" type="image/svg+xml">모든 순열의 가지치기 예시</object><object data="/ko/chapter_backtracking/permutations_problem.assets/permutations_i_pruning.dark.svg" data-theme="dark" tabindex="-1" type="image/svg+xml">모든 순열의 가지치기 예시</object></ha-svg-figure></p>
|
||||
<p align="center"> 그림 13-6 모든 순열의 가지치기 예시 </p>
|
||||
<p><ha-svg-figure aria-label="모든 순열에서 이미 선택한 원소 가지치기" class="animation-figure" data-book-key="ko/chapter_backtracking/permutations_problem.assets/permutations_i_pruning.png" data-dark-src="/assets/figure-svg/figures/f1fc5c4d6c71591f87e4a21a.json" data-figure-accessible="" data-src="/assets/figure-svg/figures/7fba710b58ba02f07fe63356.json" role="img" style=";--figure-ratio:960.0/540.0"><object aria-hidden="true" data="/ko/chapter_backtracking/permutations_problem.assets/permutations_i_pruning.svg" data-theme="light" inert="" tabindex="-1" type="image/svg+xml">모든 순열의 가지치기 예시</object><object aria-hidden="true" data="/ko/chapter_backtracking/permutations_problem.assets/permutations_i_pruning.dark.svg" data-theme="dark" inert="" tabindex="-1" type="image/svg+xml">모든 순열의 가지치기 예시</object></ha-svg-figure></p>
|
||||
<p align="center"> 그림 13-6 모든 순열의 가지치기 예시 </p><div class="ha-sr-only figure-description"><h4>그림 13-6 설명: 모든 순열에서 이미 선택한 원소 가지치기</h4><p>1 → 3 → 2 선택 경로를 따라가며 selected로 현재 순열의 접두 수열에서 이미 사용한 원소 인덱스를 가지치기한다.</p><p>입력은 중복 원소가 없는 choices = [1, 2, 3](인덱스 0, 1, 2)이며, 한 순열에서 각 원소는 한 번만 사용할 수 있다. state는 현재 순열의 접두 수열을 저장하고, 불리언 배열 selected는 입력 인덱스를 기준으로 해당 원소가 현재 경로에서 이미 선택되었는지 기록한다.</p><p>selected는 현재 재귀 경로 안에서 같은 인덱스를 중복 선택하지 못하도록 제한할 뿐이다. 아래로 재귀할 때는 이미 표시된 인덱스를 건너뛰고 되돌아올 때는 그 표시를 해제하므로, 1을 한 번 선택했다고 해서 영구히 금지되는 것은 아니며 다른 순열 가지에서는 다시 사용할 수 있다.</p><p>그림은 [] → [1] → [1, 3] → [1, 3, 2] 경로 하나만 끝까지 펼쳐 보여 준다. 가지치기 표시는 실제로 진입하지 않는 중복 선택을 뜻하며, 예를 들어 [1, 1]은 접두 수열 [1] 아래에서 인덱스 0의 원소 1을 다시 고르는 경우다. 말줄임표는 유효한 가지의 뒤쪽 과정을 생략했음을 뜻한다. 아래 표는 접두 수열별로 선택 제한과 이 두 종류의 가지를 함께 정리한다.</p><table><caption>강조된 경로의 선택 제한</caption><thead><tr><th scope="col">현재 접두 수열</th><th scope="col">사용한 인덱스(대응 값)</th><th scope="col">선택 가능한 값</th><th scope="col">그림에서 이어서 선택한 값</th><th scope="col">잘라 낸 가지와 접어 둔 가지</th></tr></thead><tbody><tr><th scope="row">[]</th><td>없음</td><td>1, 2, 3</td><td>1</td><td>가지치기 없음; [2], [3]은 유효하며 이후 생략</td></tr><tr><th scope="row">[1]</th><td>0(값 1)</td><td>2, 3</td><td>3</td><td>[1, 1] 가지치기; [1, 2]는 유효하며 이후 생략</td></tr><tr><th scope="row">[1, 3]</th><td>0(값 1), 2(값 3)</td><td>2</td><td>2</td><td>[1, 3, 1], [1, 3, 3] 가지치기; 미전개 가지 없음</td></tr></tbody></table><p>강조된 경로는 최종적으로 순열 [1, 3, 2]를 만든다.</p></div>
|
||||
<p>위 그림(13-6)에서 이 가지치기가 탐색 공간의 크기를 <span class="arithmatex">\(O(n^n)\)</span>에서 <span class="arithmatex">\(O(n!)\)</span>로 줄이는 것을 볼 수 있다.</p>
|
||||
<h3 id="2">2. 코드 구현<a class="headerlink" href="#2" title="고유 링크">¶</a></h3>
|
||||
<p>위 내용을 정리했으니 기본 틀 코드의 '빈칸을 채울' 수 있다. 전체 코드를 짧게 만들기 위해 각 함수를 따로 구현하지 않고 <code>backtrack()</code> 함수 안에 직접 작성한다.</p>
|
||||
@@ -2534,15 +2534,15 @@
|
||||
</div>
|
||||
<p>입력 배열이 <span class="arithmatex">\([1, 1, 2]\)</span>라고 하자. 두 원소 <span class="arithmatex">\(1\)</span>을 쉽게 구분하기 위해 두 번째 <span class="arithmatex">\(1\)</span>을 <span class="arithmatex">\(\hat{1}\)</span>로 표시한다.</p>
|
||||
<p>아래 그림(13-7)과 같이 앞의 방법으로 만든 순열의 절반은 중복된다.</p>
|
||||
<p><ha-svg-figure class="animation-figure" data-book-key="ko/chapter_backtracking/permutations_problem.assets/permutations_ii.png" data-dark-src="/assets/figure-svg/figures/7633ec940e1eac4237127f85.json" data-src="/assets/figure-svg/figures/300e02a59e6a04081a9f0878.json" style=";--figure-ratio:960.0/540.0"><object data="/ko/chapter_backtracking/permutations_problem.assets/permutations_ii.svg" data-theme="light" tabindex="-1" type="image/svg+xml">중복된 순열</object><object data="/ko/chapter_backtracking/permutations_problem.assets/permutations_ii.dark.svg" data-theme="dark" tabindex="-1" type="image/svg+xml">중복된 순열</object></ha-svg-figure></p>
|
||||
<p align="center"> 그림 13-7 중복된 순열 </p>
|
||||
<p><ha-svg-figure aria-label="값이 같은 원소로 인해 중복되는 순열" class="animation-figure" data-book-key="ko/chapter_backtracking/permutations_problem.assets/permutations_ii.png" data-dark-src="/assets/figure-svg/figures/7633ec940e1eac4237127f85.json" data-figure-accessible="" data-src="/assets/figure-svg/figures/300e02a59e6a04081a9f0878.json" role="img" style=";--figure-ratio:960.0/540.0"><object aria-hidden="true" data="/ko/chapter_backtracking/permutations_problem.assets/permutations_ii.svg" data-theme="light" inert="" tabindex="-1" type="image/svg+xml">중복된 순열</object><object aria-hidden="true" data="/ko/chapter_backtracking/permutations_problem.assets/permutations_ii.dark.svg" data-theme="dark" inert="" tabindex="-1" type="image/svg+xml">중복된 순열</object></ha-svg-figure></p>
|
||||
<p align="center"> 그림 13-7 중복된 순열 </p><div class="ha-sr-only figure-description"><h3>그림 13-7 설명: 값이 같은 원소로 인해 중복되는 순열</h3><p>값이 1인 두 원소를 서로 다른 후보로 보고 펼치면 여섯 개의 경로가 생기지만 서로 다른 값의 순열은 세 가지뿐이다.</p><p>입력 배열은 choices = [1, 1, 2]이고 인덱스는 차례로 0, 1, 2다. 아래에서는 인덱스 0과 1을 ‘첫 번째 1’과 ‘두 번째 1’로 구분하며, 원본 그림에서는 두 번째 1 위에 모자 기호(^)를 붙여 구분하지만 두 원소의 실제 값은 모두 1이다. 한 순열 경로에서 각 인덱스는 최대 한 번만 쓰이지만 selected로 인덱스 재사용만 막으면 값이 같은 순열이 여전히 만들어진다.</p><p>맨 위 state에는 빈 슬롯 세 개가 있다. 파란색 칸은 첫 번째 1, 청록색 칸은 두 번째 1, 보라색 칸은 2를 나타낸다. 세 차례의 선택에서 아직 사용하지 않은 인덱스를 차례로 채우면 아래 표의 리프 노드 여섯 개로 펼쳐진다. 3, 4, 6번째 항목에는 주황색 테두리가 둘러져 있으며 함께 ‘제거해야 할 중복 순열’을 가리킨다. 표의 순번은 왼쪽에서 오른쪽 순서로 매겼고, 유지 및 중복 짝 관계는 그림의 주황색 테두리와 순열 값에 따라 정리했다.</p><table><caption>여섯 리프 노드와 중복 짝 관계</caption><thead><tr><th scope="col">리프 노드 순번(왼쪽에서 오른쪽)</th><th scope="col">원소를 구별해 적은 순열</th><th scope="col">그림 표시 및 정리</th></tr></thead><tbody><tr><th scope="row">1</th><td>[첫 번째 1, 두 번째 1, 2]</td><td>주황색 테두리 없음, 유지</td></tr><tr><th scope="row">2</th><td>[첫 번째 1, 2, 두 번째 1]</td><td>주황색 테두리 없음, 유지</td></tr><tr><th scope="row">3</th><td>[두 번째 1, 첫 번째 1, 2]</td><td>주황색 테두리, 1번째 항목과 중복</td></tr><tr><th scope="row">4</th><td>[두 번째 1, 2, 첫 번째 1]</td><td>주황색 테두리, 2번째 항목과 중복</td></tr><tr><th scope="row">5</th><td>[2, 첫 번째 1, 두 번째 1]</td><td>주황색 테두리 없음, 유지</td></tr><tr><th scope="row">6</th><td>[2, 두 번째 1, 첫 번째 1]</td><td>주황색 테두리, 5번째 항목과 중복</td></tr></tbody></table><p>원소를 구별하는 표시를 걷어 내면 여섯 리프 노드는 [1, 1, 2], [1, 2, 1], [2, 1, 1]이라는 중복 없는 세 가지 값 순열에만 대응한다.</p></div>
|
||||
<p>중복된 순열은 어떻게 제거할까? 가장 직접적으로는 해시 집합을 이용해 결과에서 중복을 제거할 수 있다. 하지만 이 방법은 충분히 간결하지 않다. <strong>중복된 순열을 만드는 탐색 가지는 불필요하므로 미리 알아내어 잘라 내야 하며</strong>, 그러면 알고리즘의 효율을 더 높일 수 있다.</p>
|
||||
<h3 id="1_1">1. 같은 값의 원소 가지치기<a class="headerlink" href="#1_1" title="고유 링크">¶</a></h3>
|
||||
<p>아래 그림(13-8)에서 첫 번째 선택으로 <span class="arithmatex">\(1\)</span>을 고르든 <span class="arithmatex">\(\hat{1}\)</span>을 고르든 같다. 두 선택 아래에서 만들어지는 모든 순열이 중복되므로 <span class="arithmatex">\(\hat{1}\)</span>을 가지치기해야 한다.</p>
|
||||
<p>마찬가지로 첫 번째에 <span class="arithmatex">\(2\)</span>를 선택한 뒤에도 두 번째의 <span class="arithmatex">\(1\)</span>과 <span class="arithmatex">\(\hat{1}\)</span>이 중복 가지를 만들므로 두 번째의 <span class="arithmatex">\(\hat{1}\)</span>도 잘라 내야 한다.</p>
|
||||
<p>본질적으로 <strong>한 차례의 선택에서 값이 같은 여러 원소를 한 번만 선택하도록 보장하는 것</strong>이 목표다.</p>
|
||||
<p><ha-svg-figure class="animation-figure" data-book-key="ko/chapter_backtracking/permutations_problem.assets/permutations_ii_pruning.png" data-dark-src="/assets/figure-svg/figures/8b6c415c7742a2431f9ac822.json" data-src="/assets/figure-svg/figures/3c6095d9d97fbee3a2a2612a.json" style=";--figure-ratio:960.0/540.0"><object data="/ko/chapter_backtracking/permutations_problem.assets/permutations_ii_pruning.svg" data-theme="light" tabindex="-1" type="image/svg+xml">중복된 순열 가지치기</object><object data="/ko/chapter_backtracking/permutations_problem.assets/permutations_ii_pruning.dark.svg" data-theme="dark" tabindex="-1" type="image/svg+xml">중복된 순열 가지치기</object></ha-svg-figure></p>
|
||||
<p align="center"> 그림 13-8 중복된 순열 가지치기 </p>
|
||||
<p><ha-svg-figure aria-label="같은 차례에서 값이 같은 원소의 가지치기" class="animation-figure" data-book-key="ko/chapter_backtracking/permutations_problem.assets/permutations_ii_pruning.png" data-dark-src="/assets/figure-svg/figures/8b6c415c7742a2431f9ac822.json" data-figure-accessible="" data-src="/assets/figure-svg/figures/3c6095d9d97fbee3a2a2612a.json" role="img" style=";--figure-ratio:960.0/540.0"><object aria-hidden="true" data="/ko/chapter_backtracking/permutations_problem.assets/permutations_ii_pruning.svg" data-theme="light" inert="" tabindex="-1" type="image/svg+xml">중복된 순열 가지치기</object><object aria-hidden="true" data="/ko/chapter_backtracking/permutations_problem.assets/permutations_ii_pruning.dark.svg" data-theme="dark" inert="" tabindex="-1" type="image/svg+xml">중복된 순열 가지치기</object></ha-svg-figure></p>
|
||||
<p align="center"> 그림 13-8 중복된 순열 가지치기 </p><div class="ha-sr-only figure-description"><h4>그림 13-8 설명: 같은 차례에서 값이 같은 원소의 가지치기</h4><p>같은 선택 차례에서 같은 값 1을 한 번만 시도하여 중복되는 탐색 서브트리를 미리 잘라 낸다.</p><p>입력 배열은 choices = [1, 1, 2]이고 인덱스는 차례로 0, 1, 2다. 아래에서는 인덱스 0과 1을 ‘첫 번째 1’과 ‘두 번째 1’로 구분하며, 원본 그림에서는 두 번째 1 위에 모자 기호(^)를 붙여 구분하지만 두 원소의 실제 값은 모두 1이다.</p><p>두 제약은 각각 인덱스와 값을 담당한다. selected는 현재 경로에서 이미 사용한 인덱스를 기록하고, 본문 코드의 중복 제거 집합 duplicated는 이번 차례에서 selected로 건너뛰지 않고 실제로 선택한 값을 기록한다. 재귀 호출마다 고유한 duplicated를 새로 만들며, 되돌리기 단계에서는 selected와 state만 복원하고 현재 호출의 집합에 이미 기록된 값은 지우지 않는다.</p><p>그림에는 루트 []와 접두 수열 [2] 아래에서 두 번째 1을 건너뛰는 같은 차례 가지치기 두 곳만 표시되어 있다. 아래 ‘각 접두 수열의 한 차례 선택’ 표는 종료 전 여섯 접두 수열의 선택과 제외를 모두 보충한 것으로, 그중 ‘사용한 인덱스로 건너뜀’ 열은 코드 규칙에 따라 추론한 것이며 이 그림에 직접 가지치기 표시가 그려진 것은 아니다. ‘중복 없는 세 순열’ 표는 리프 노드의 원소 구별 표기와 실제 값 결과를 나열한다.</p><table><caption>각 접두 수열의 한 차례 선택</caption><thead><tr><th scope="col">현재 접두 수열</th><th scope="col">유지한 후보</th><th scope="col">사용한 인덱스로 건너뜀</th><th scope="col">같은 차례의 중복 값으로 건너뜀</th></tr></thead><tbody><tr><th scope="row">[]</th><td>첫 번째 1, 2</td><td>없음</td><td>두 번째 1: 이번 차례에 이미 값 1을 시도함</td></tr><tr><th scope="row">[첫 번째 1]</th><td>두 번째 1, 2</td><td>첫 번째 1: 인덱스 0이 이미 경로에 있음</td><td>없음</td></tr><tr><th scope="row">[첫 번째 1, 두 번째 1]</th><td>2</td><td>첫 번째 1, 두 번째 1: 해당 인덱스를 모두 이미 사용함</td><td>없음</td></tr><tr><th scope="row">[첫 번째 1, 2]</th><td>두 번째 1</td><td>첫 번째 1, 2: 해당 인덱스를 모두 이미 사용함</td><td>없음</td></tr><tr><th scope="row">[2]</th><td>첫 번째 1</td><td>2: 인덱스 2가 이미 경로에 있음</td><td>두 번째 1: 이번 차례에 이미 값 1을 시도함</td></tr><tr><th scope="row">[2, 첫 번째 1]</th><td>두 번째 1</td><td>2, 첫 번째 1: 해당 인덱스를 모두 이미 사용함</td><td>없음</td></tr></tbody></table><table><caption>중복 없는 세 순열</caption><thead><tr><th scope="col">결과 순번</th><th scope="col">두 1을 구별한 표기</th><th scope="col">실제 값 결과</th></tr></thead><tbody><tr><th scope="row">1</th><td>[첫 번째 1, 두 번째 1, 2]</td><td>[1,1,2]</td></tr><tr><th scope="row">2</th><td>[첫 번째 1, 2, 두 번째 1]</td><td>[1,2,1]</td></tr><tr><th scope="row">3</th><td>[2, 첫 번째 1, 두 번째 1]</td><td>[2,1,1]</td></tr></tbody></table><p>한 경로 안에서 인덱스가 다른 두 개의 1을 앞뒤 차례로 고를 수는 있지만, 같은 차례에서는 값 1에 대해 하나의 가지만 펼친다.</p></div>
|
||||
<h3 id="2_1">2. 코드 구현<a class="headerlink" href="#2_1" title="고유 링크">¶</a></h3>
|
||||
<p>앞 문제의 코드를 바탕으로 매 차례의 선택에서 해시 집합 <code>duplicated</code>를 만들어 이미 시도한 원소를 기록하고 중복 원소를 가지치기한다.</p>
|
||||
<div class="tabbed-set tabbed-alternate" data-tabs="2:13"><input checked="checked" id="__tabbed_2_1" name="__tabbed_2" type="radio"/><input id="__tabbed_2_2" name="__tabbed_2" type="radio"/><input id="__tabbed_2_3" name="__tabbed_2" type="radio"/><input id="__tabbed_2_4" name="__tabbed_2" type="radio"/><input id="__tabbed_2_5" name="__tabbed_2" type="radio"/><input id="__tabbed_2_6" name="__tabbed_2" type="radio"/><input id="__tabbed_2_7" name="__tabbed_2" type="radio"/><input id="__tabbed_2_8" name="__tabbed_2" type="radio"/><input id="__tabbed_2_9" name="__tabbed_2" type="radio"/><input id="__tabbed_2_10" name="__tabbed_2" type="radio"/><input id="__tabbed_2_11" name="__tabbed_2" type="radio"/><input id="__tabbed_2_12" name="__tabbed_2" type="radio"/><input id="__tabbed_2_13" name="__tabbed_2" type="radio"/><div class="tabbed-labels"><label for="__tabbed_2_1">Python</label><label for="__tabbed_2_2">C++</label><label for="__tabbed_2_3">Java</label><label for="__tabbed_2_4">C#</label><label for="__tabbed_2_5">Go</label><label for="__tabbed_2_6">Swift</label><label for="__tabbed_2_7">JS</label><label for="__tabbed_2_8">TS</label><label for="__tabbed_2_9">Dart</label><label for="__tabbed_2_10">Rust</label><label for="__tabbed_2_11">C</label><label for="__tabbed_2_12">Kotlin</label><label for="__tabbed_2_13">Ruby</label></div>
|
||||
@@ -3047,8 +3047,8 @@
|
||||
<li><strong>같은 값의 원소 가지치기</strong>: 매 차례의 선택(호출된 각 <code>backtrack</code> 함수)마다 <code>duplicated</code>가 하나씩 있다. 이번 순회(<code>for</code> 반복문)에서 이미 선택한 원소를 기록하여 같은 값의 원소를 한 번만 선택하게 한다.</li>
|
||||
</ul>
|
||||
<p>아래 그림(13-9)은 두 가지 가지치기 조건이 적용되는 범위를 보여 준다. 각 트리 노드는 선택 하나를 나타내며, 루트에서 리프까지의 경로에 있는 노드들이 하나의 순열을 이룬다.</p>
|
||||
<p><ha-svg-figure class="animation-figure" data-book-key="ko/chapter_backtracking/permutations_problem.assets/permutations_ii_pruning_summary.png" data-dark-src="/assets/figure-svg/figures/5e783debff38402d926ac69d.json" data-src="/assets/figure-svg/figures/a163872453544a9c4c27c273.json" style=";--figure-ratio:960.0/540.0"><object data="/ko/chapter_backtracking/permutations_problem.assets/permutations_ii_pruning_summary.svg" data-theme="light" tabindex="-1" type="image/svg+xml">두 가지 가지치기 조건의 적용 범위</object><object data="/ko/chapter_backtracking/permutations_problem.assets/permutations_ii_pruning_summary.dark.svg" data-theme="dark" tabindex="-1" type="image/svg+xml">두 가지 가지치기 조건의 적용 범위</object></ha-svg-figure></p>
|
||||
<p align="center"> 그림 13-9 두 가지 가지치기 조건의 적용 범위 </p>
|
||||
<p><ha-svg-figure aria-label="인덱스와 값을 각각 제한하는 두 가지 순열 가지치기" class="animation-figure" data-book-key="ko/chapter_backtracking/permutations_problem.assets/permutations_ii_pruning_summary.png" data-dark-src="/assets/figure-svg/figures/5e783debff38402d926ac69d.json" data-figure-accessible="" data-src="/assets/figure-svg/figures/a163872453544a9c4c27c273.json" role="img" style=";--figure-ratio:960.0/540.0"><object aria-hidden="true" data="/ko/chapter_backtracking/permutations_problem.assets/permutations_ii_pruning_summary.svg" data-theme="light" inert="" tabindex="-1" type="image/svg+xml">두 가지 가지치기 조건의 적용 범위</object><object aria-hidden="true" data="/ko/chapter_backtracking/permutations_problem.assets/permutations_ii_pruning_summary.dark.svg" data-theme="dark" inert="" tabindex="-1" type="image/svg+xml">두 가지 가지치기 조건의 적용 범위</object></ha-svg-figure></p>
|
||||
<p align="center"> 그림 13-9 두 가지 가지치기 조건의 적용 범위 </p><div class="ha-sr-only figure-description"><h4>그림 13-9 설명: 인덱스와 값을 각각 제한하는 두 가지 순열 가지치기</h4><p>경로 내 인덱스 중복 금지(selected)와 같은 차례의 값 중복 금지(duplicated)라는 두 가지 가지치기 조건을 나란히 비교한다.</p><p>입력 배열은 choices = [1, 1, 2]이고 인덱스는 차례로 0, 1, 2다. 아래에서는 인덱스 0과 1을 ‘첫 번째 1’과 ‘두 번째 1’로 구분하며, 원본 그림에서는 두 번째 1 위에 모자 기호(^)를 붙여 구분하지만 두 원소의 실제 값은 모두 1이다.</p><p>검은 가위는 경로 인덱스 가지치기를 나타내며, 현재 경로에서 이미 사용한 인덱스를 다시 쓰지 못하게 막고 되돌아오면 그 인덱스를 다시 사용할 수 있게 복원한다. 빨간 가위는 같은 차례 값 가지치기를 나타내며, duplicated는 현재 호출의 이번 차례에서 검은 가위로 건너뛰지 않고 실제로 선택한 값만 기록하고 재귀 호출마다 새로 생성되므로 selected와 적용 범위가 다르다.</p><p>이 그림에서 각 사각형 노드는 선택 하나를 나타내며, 표의 접두 수열은 루트에서 해당 노드까지의 경로를 이은 것이고 루트에서 리프까지의 전체 경로가 순열 하나를 이룬다. 아래 첫 번째 표는 그림의 검은 가위와 빨간 가위를 두 열로 나누어 정리하며, 한 칸에 여러 후보가 적힌 경우 잘려 나간 여러 가지에 대응한다. 루트 []와 접두 수열 [2] 아래의 두 번째 1은 빨간 가위로 잘리고, 이미 사용한 인덱스의 나머지 가지는 검은 가위로 잘린다. 두 번째 표는 순번별로 중복 없는 세 순열을 나열한다.</p><table><caption>각 접두 수열의 한 차례 선택</caption><thead><tr><th scope="col">현재 접두 수열</th><th scope="col">유지한 후보</th><th scope="col">검은 가위: 사용한 인덱스로 건너뜀</th><th scope="col">빨간 가위: 같은 차례의 중복 값으로 건너뜀</th></tr></thead><tbody><tr><th scope="row">[]</th><td>첫 번째 1, 2</td><td>없음</td><td>두 번째 1: 이번 차례에 이미 값 1을 시도함</td></tr><tr><th scope="row">[첫 번째 1]</th><td>두 번째 1, 2</td><td>첫 번째 1: 인덱스 0이 이미 경로에 있음</td><td>없음</td></tr><tr><th scope="row">[첫 번째 1, 두 번째 1]</th><td>2</td><td>첫 번째 1, 두 번째 1: 해당 인덱스를 모두 이미 사용함</td><td>없음</td></tr><tr><th scope="row">[첫 번째 1, 2]</th><td>두 번째 1</td><td>첫 번째 1, 2: 해당 인덱스를 모두 이미 사용함</td><td>없음</td></tr><tr><th scope="row">[2]</th><td>첫 번째 1</td><td>2: 인덱스 2가 이미 경로에 있음</td><td>두 번째 1: 이번 차례에 이미 값 1을 시도함</td></tr><tr><th scope="row">[2, 첫 번째 1]</th><td>두 번째 1</td><td>2, 첫 번째 1: 해당 인덱스를 모두 이미 사용함</td><td>없음</td></tr></tbody></table><table><caption>중복 없는 세 순열</caption><thead><tr><th scope="col">결과 순번</th><th scope="col">두 1을 구별한 표기</th><th scope="col">실제 값 결과</th></tr></thead><tbody><tr><th scope="row">1</th><td>[첫 번째 1, 두 번째 1, 2]</td><td>[1,1,2]</td></tr><tr><th scope="row">2</th><td>[첫 번째 1, 2, 두 번째 1]</td><td>[1,2,1]</td></tr><tr><th scope="row">3</th><td>[2, 첫 번째 1, 두 번째 1]</td><td>[2,1,1]</td></tr></tbody></table><p>한 경로 안에서 인덱스가 다른 두 개의 1을 앞뒤 차례로 고를 수는 있지만, 같은 차례에서는 값 1에 대해 하나의 가지만 펼친다.</p></div>
|
||||
<!-- Source file information -->
|
||||
<!-- Was this page helpful? -->
|
||||
<!-- Previous and next pages link -->
|
||||
@@ -3170,5 +3170,5 @@
|
||||
<script src="../../javascripts/mathjax.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.2/es5/tex-mml-chtml.min.js"></script>
|
||||
<script src="../../javascripts/animation_player.js"></script>
|
||||
<script defer="" src="/assets/figure-svg/js/bcdea376f01bc2bc0cac7c6c.js"></script><script defer="" src="/assets/figure-svg/js/e84f59519170c0f5ef238548.js"></script><script defer="" src="/assets/figure-svg/js/a704d8e80a80ddc71f2a03a7.js"></script><script defer="" src="/assets/figure-svg/js/bff17b8259339758cb1c4a06.js"></script></body>
|
||||
<script defer="" src="/assets/figure-svg/js/00174ff861e190f5c1f09e34.js"></script><script defer="" src="/assets/figure-svg/js/e84f59519170c0f5ef238548.js"></script><script defer="" src="/assets/figure-svg/js/a704d8e80a80ddc71f2a03a7.js"></script><script defer="" src="/assets/figure-svg/js/70ae82c6406c9bdbda8e8362.js"></script></body>
|
||||
</html>
|
||||
Binary file not shown.
Reference in New Issue
Block a user