本文へスキップ
製品デスクトップツール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
ディスカッション

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

Backtracking in the Real World

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

Backtracking is more than an interview technique. It runs inside tools you use every day: regular expression engines, SAT solvers, constraint programming libraries, and logic programming languages. This chapter covers where it shows up, the pitfalls you meet in production code, and where to read more.

Where backtracking runs

  • Regular expression engines: Python re, Java java.util.regex, JavaScript, and PCRE try each alternative of a pattern (|, *, +) in turn and back up on failure. That is what makes features like backreferences possible, and also why some inputs take exponential time.
  • SAT solvers and DPLL: the DPLL algorithm assigns Boolean variables one at a time and backtracks on a contradiction. It is the foundation of modern CDCL SAT solvers used in hardware verification and package dependency resolution.
  • Constraint programming: solvers such as Google OR-Tools CP-SAT model timetables, shift rosters, and production schedules as variables and constraints, and use constraint propagation to prune branches before exploring them.
  • Logic programming: in Prolog, trying rules from the top and falling back to the next rule on failure is the execution model itself.
  • Puzzles and games: Sudoku, crossword, and exact cover solvers (Knuth's Dancing Links) are classic examples.
  • Parsers: PEG parsers and some recursive descent parsers try grammar alternatives in order and rewind the input position when one fails.

Pitfall 1: catastrophic backtracking in regexes

A pattern like (a+)+$ can split a run of a characters in exponentially many ways, so on input whose ending does not match, the engine tries every split. Applying such a pattern to user-supplied text opens the door to a denial-of-service attack (ReDoS).

import re
import time

pattern = re.compile(r"(a+)+$")
for n in (16, 18, 20, 22):
    text = "a" * n + "!"
    start = time.perf_counter()
    pattern.match(text)
    print(n, f"{time.perf_counter() - start:.3f}s")
# every extra character roughly doubles the time

Fixes include removing the nested repetition (a+$ matches the same strings here), limiting input length, or switching to an engine with linear-time guarantees such as RE2.

Pitfall 2: recursion depth and copying

Python's default recursion limit is around 1000, so searches thousands of levels deep raise RecursionError. You can raise the limit with sys.setrecursionlimit, but that risks overflowing the C stack; for deep searches an explicit stack is safer.

def subsets_iterative(nums):
    result = []
    stack = [(0, [])]                 # (next index, partial solution)
    while stack:
        i, path = stack.pop()
        if i == len(nums):
            result.append(path)
            continue
        stack.append((i + 1, path))               # branch that skips nums[i]
        stack.append((i + 1, path + [nums[i]]))   # branch that takes it
    return result

print(subsets_iterative([1, 2]))  # [[1, 2], [1], [2], []]
この章について質問がありますか?
前の章Practice Problems

An explicit stack copies state instead of undoing it, so it uses more memory. When the depth is modest, the recursive version is simpler and faster.

Pitfall 3: reinventing the standard library

For plain permutations, combinations, or Cartesian products, the standard library is faster and already tested. Write your own backtracking when you need to prune along the way.

from itertools import combinations, permutations, product

print(list(combinations("ABC", 2)))   # [('A', 'B'), ('A', 'C'), ('B', 'C')]
print(len(list(permutations(range(4)))))  # 24
print(list(product([0, 1], repeat=2)))     # [(0, 0), (0, 1), (1, 0), (1, 1)]

Other things to watch

  • A missing or misordered undo leaks state into other branches, and the results go quietly wrong. Always write choose and unchoose as a pair.
  • A pruning rule that is too aggressive cuts off branches that contain real solutions. For small inputs, keep a test that compares against brute force.
  • If input sizes can grow, estimate the worst-case search size up front and add a time or node budget so the service never hangs.
  • Real scheduling problems with complex constraints are usually better handed to a solver such as CP-SAT than implemented by hand.

Summary

  • Backtracking is the core engine of practical tools: regex engines, SAT solvers, constraint programming, and Prolog.
  • Catastrophic backtracking, recursion depth, and forgotten undo steps are the most common production problems.
  • Leave standard enumerations to the library and hard constraint problems to dedicated solvers; implement backtracking yourself where custom pruning pays off.

Further reading

  • Backtracking (Wikipedia)
  • Eight queens puzzle (Wikipedia)
  • Sudoku solving algorithms (Wikipedia)
  • Constraint satisfaction problem (Wikipedia)
  • itertools (Python documentation)
  • Constraint Optimization (Google OR-Tools)
  • Regular expression Denial of Service - ReDoS (OWASP)

コメント 0件

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

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