本文へスキップ
製品デスクトップツールTASTECAD図面の確認TASTEFILESファイル管理TASTEFTPファイル転送TASTESSHリモートワークスペースTASTEZIP圧縮と展開TASTEWINMファイル管理開発ツールTASTECODERust 統合開発環境TASTESTUDIO統合開発・テスト環境TASTEETLデータ統合(ETL)サーバーTASTEREMOTEリモートデスクトップサーバーTASTEGEO空間情報サーバーTASTEMAILメールワークスペース投資TASTESTOCK株式自動売買デスクトップアプリはじめるダウンロードドキュメント購入すべての製品
マーケットプレイス
ニュース
技術ニュース今日の開発ニュース開発ドキュメントプログラミング言語RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWebフロントエンド フレームワークNext.jsReactVue.js · NuxtSvelteKitAngularサーバー フレームワークSpring BootDjangoFastAPIASP.NET CoreNestJS · Expressアプリ・デスクトップ フレームワークTauriFlutterReact NativeElectronアルゴリズムアルゴリズムの基礎主要アルゴリズム発展アルゴリズム実務のアルゴリズム
コミュニティプロジェクト開発ログプロンプトAIツールの問題ショーケースコミュニティガイド
協業技術移転ウェブサイト構築デスクトップアプリ構築リリース・決済パイプライン販売パートナーお問い合わせ
サービスリモートデスクトップインストールパッケージのカスタマイズ
TASTEDEV
製品

デスクトップツール

TASTECAD複雑な図面を、軽やかにひらくTASTEFILES必要なファイルだけを、最速でTASTEFTPファイルが行き交う、いちばん端正な道TASTESSHサーバーとあなたを、より確かにつなぐTASTEZIPより速くまとめ、より安全にひらくTASTEWINM2つの画面で整理する、キーボード中心のファイルマネージャー

開発ツール

TASTECODERust アプリの編集・ビルド・デバッグ・テストまでひとつのウィンドウでTASTESTUDIO編集からリモートテスト、承認した AI 修正までTASTEETL値を見ながら、データを運ぶ

サーバー

TASTEREMOTE自社サーバーで運用するリモートデスクトップTASTEGEOGeoServer 互換の空間情報サーバーを Rust で作り直しますTASTEMAILメールの主導権を、もう一度自分の手に

投資

TASTESTOCKいつ・何を。自分で決めたルールどおりに動く株式自動売買

はじめる

ダウンロード全製品の最新版ドキュメント各製品の使い方購入サブスクリプション・永久ライセンスすべての製品全製品を一覧で
すべての製品
マーケットプレイスニュース
技術

ニュース

今日の開発ニュース言語・フレームワーク・GitHub・AI の公式発表開発ドキュメント言語・フレームワーク・アルゴリズムのガイド

プログラミング言語

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

フレームワーク

Webフロントエンド フレームワークNext.jsReactVue.js · NuxtSvelteKitAngular
サーバー フレームワークSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
アプリ・デスクトップ フレームワークTauriFlutterReact NativeElectron

アルゴリズム

アルゴリズムの基礎計算量解析 · ソート · 探索 · 基本データ構造 · 木構造とヒープ主要アルゴリズムグラフ探索 · 最短経路と最小全域木 · 動的計画法 · 貪欲法 · 分割統治法 · バックトラッキング発展アルゴリズム文字列アルゴリズム · 数学と整数論 · ビット演算 · セグメント木 · Union-Find実務のアルゴリズムコーディング面接対策 · LRUキャッシュ · レート制限 · コンシステントハッシュ法
開発ドキュメントをすべて見る
コミュニティ
プロジェクトビルダーと作品を探す開発ログ決定と試行錯誤プロンプト再利用できる指示AIツールの問題Claude・Codex・Gemini の問題と回避策ショーケース完成した成果コミュニティガイドオープンにつくる方法
協業
技術移転Rust・egui でネイティブアプリを作るウェブサイト構築10言語、アカウント、ドキュメントとダウンロードデスクトップアプリ構築Rust・egui、WebView なしリリース・決済パイプライン署名・MSI・deb・rpm・AppImage・ハッシュ販売パートナー紹介して決済額の30%お問い合わせ構築・提携・投資のご相談
サービス
リモートデスクトップブラウザから自分のパソコンへインストールパッケージのカスタマイズ必要な機能だけ、設定は事前に
購入
JA
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
ログイン
ログイン
TASTEDEV

小さなツールから、より良い開発へ。

support@tastedev.netTASTEDEVを支援
製品製品ラインナップ購入ドキュメントダウンロードマーケットプレイスサポート
コミュニティプロジェクト開発ログプロンプトAIツールの問題ショーケース
ポリシー会社概要プライバシーポリシー利用規約サブスクリプション規約返金ポリシーコミュニティガイドライン
アカウントログイン新規登録
訪問者
今日
昨日
累計閲覧
商号
GXSOFT
代表者
CHOI YOUNG GU
事業者登録番号
853-44-00368
所在地
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
電話
+82-10-4404-1523
メール
whitecalvin@tastedev.net
個人情報保護責任者
CHOI YOUNG GU

© 2026 TASTEDEV製品情報は検証済みの開発ソースに基づいています。リリース・改善中

バックトラッキング ドキュメント
バックトラッキング
Backtracking ConceptsHow It WorksImplementationComplexityPractice ProblemsBacktracking in the Real World
ディスカッション

バックトラッキング ガイド · 5/6

Practice Problems

この章は現在、英語でのみ提供しています。

Backtracking problems look different on the surface, but once you decide what counts as one step and when to prune, most of them fit the same template. Try the four problems below on your own first, then compare your approach with the one given.

Problem 1: balanced parentheses

Given an integer n, list every valid string made of n opening and n closing parentheses. For n = 2 the answer is (()) and ()().

Approach: append one character at a time. An opening parenthesis is allowed only while fewer than n have been used, and a closing one only while fewer have been closed than opened. These two rules are the pruning that prevents invalid strings from ever being built.

def parentheses(n):
    out = []

    def dfs(s, opened, closed):
        if len(s) == 2 * n:
            out.append(s)
            return
        if opened < n:
            dfs(s + "(", opened + 1, closed)
        if closed < opened:
            dfs(s + ")", opened, closed + 1)

    dfs("", 0, 0)
    return out

print(parentheses(3))
# ['((()))', '(()())', '(())()', '()(())', '()()()']

Problem 2: find a word in a grid

You are given a 2D grid of letters and a word. Decide whether the word can be spelled by moving between horizontally or vertically adjacent cells, using each cell at most once.

Approach: start a search from every cell. Mark the current cell as in use by overwriting it with # (choose), look for the next letter in four directions (explore), then restore the original letter (unchoose). Return immediately when a letter does not match.

def exists(grid, word):
    rows, cols = len(grid), len(grid[0])

    def dfs(r, c, i):
        if i == len(word):
            return True
        if not (0 <= r < rows and 0 <= c < cols) or grid[r][c] != word[i]:
            return False
        saved, grid[r][c] = grid[r][c], "#"
        found = any(dfs(r + dr, c + dc, i + 1)
                    for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)))
        grid[r][c] = saved
        return found

    return any(dfs(r, c, 0) for r in range(rows) for c in range(cols))

board = [list("CAT"), list("OXD"), list("DEN")]
print(exists(board, "CODE"), exists(board, "COAT"))  # True False

Problem 3: permutations with duplicates

List the distinct permutations of a list that contains repeated values, such as [1, 1, 2]. No permutation may appear twice in the output.

Approach: sort first. Picking the same value twice at the same depth repeats an identical branch, so skip a value when the equal value right before it has not been used yet. This shrinks the search itself, which is better than generating duplicates and removing them with a set.

この章について質問がありますか?
前の章Complexity次の章Backtracking in the Real World
def unique_permutations(nums):
    nums = sorted(nums)
    used = [False] * len(nums)
    result, path = [], []

    def dfs():
        if len(path) == len(nums):
            result.append(path[:])
            return
        for i in range(len(nums)):
            if used[i]:
                continue
            if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]:
                continue
            used[i] = True
            path.append(nums[i])
            dfs()
            path.pop()
            used[i] = False

    dfs()
    return result

print(unique_permutations([1, 1, 2]))  # [[1, 1, 2], [1, 2, 1], [2, 1, 1]]

Problem 4: solve a Sudoku

Fill in a 9x9 Sudoku board where empty cells are marked with 0. Assume the puzzle has a solution.

Approach: keep a set of used digits for each row, column, and box so each constraint check is O(1). Fill the empty cells in order; when no digit fits, return False so the previous cell tries its next digit. Once a solution is found, pass True upward so nothing gets undone.

def solve_sudoku(board):
    rows = [set() for _ in range(9)]
    cols = [set() for _ in range(9)]
    boxes = [set() for _ in range(9)]
    empty = []
    for r in range(9):
        for c in range(9):
            d = board[r][c]
            if d:
                rows[r].add(d); cols[c].add(d); boxes[r // 3 * 3 + c // 3].add(d)
            else:
                empty.append((r, c))

    def fill(k):
        if k == len(empty):
            return True
        r, c = empty[k]
        b = r // 3 * 3 + c // 3
        for d in range(1, 10):
            if d in rows[r] or d in cols[c] or d in boxes[b]:
                continue
            board[r][c] = d
            rows[r].add(d); cols[c].add(d); boxes[b].add(d)
            if fill(k + 1):
                return True
            rows[r].remove(d); cols[c].remove(d); boxes[b].remove(d)
        board[r][c] = 0
        return False

    return fill(0)

To make it faster, always fill the remaining cell with the fewest candidates next (MRV). On hard puzzles this cuts the number of visited nodes dramatically.

Summary

  • Decide the unit of one step (a character, a cell, an element) and the pruning rule first; the code then follows the usual template.
  • Rather than filtering duplicate solutions afterwards, block identical choices at the same depth so they are never generated.
  • When one solution is enough, return True to end the search early.

コメント 0件

人気のコメント順新しい順

ログイン · ログインするとコメントできます。