ENع
→Backtracking
الدرس 44 · Dynamic programming and backtracking

Backtracking: subsets and permutations

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

14 دقيقة9 خطوات5 أسئلةAdvanced
عن هذا الدرس

Some problems have no clever shortcut: you have to try every option. Backtracking does that in an orderly way. It draws the options as a tree of choices and walks it depth first with one shared list, using three moves: choose, explore, un-choose. Watch it list all 8 subsets and all 6 orders of [1, 2, 3], then count what the search costs. The Software lessons "Recursion" and "Dynamic programming" cover the recursive calls and the reuse of answers that this lesson builds on.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 44 · تفاعلي
01 / 09

A tree of choices

Goal: list every subset of [1, 2, 3]. Each number is one yes-or-no choice: take it (left edge) or skip it (right edge). Three choices make 2 × 2 × 2 = 8 leaves, one per subset. Each block shows the list chosen so far.

nums = [1, 2, 3]
level 0: decide 1    level 1: decide 2    level 2: decide 3
left edge = take     right edge = skip

leaves: 2 × 2 × 2 = 8
[1, 2, 3]  [1, 2]  [1, 3]  [1]  [2, 3]  [2]  [3]  []
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. A tree of choices

    Goal: list every subset of [1, 2, 3]. Each number is one yes-or-no choice: take it (left edge) or skip it (right edge). Three choices make 2 × 2 × 2 = 8 leaves, one per subset. Each block shows the list chosen so far.

    nums = [1, 2, 3]
    level 0: decide 1    level 1: decide 2    level 2: decide 3
    left edge = take     right edge = skip
    
    leaves: 2 × 2 × 2 = 8
    [1, 2, 3]  [1, 2]  [1, 3]  [1]  [2, 3]  [2]  [3]  []
  2. One shared list: path

    The code walks this tree by recursion. Each call is one block, and the rose puck marks the call running now. One shared list, path, holds the choices made so far. Going down an edge changes path; coming back up must undo it.

     1  def subsets(nums, i, path, out):
     2      if i == len(nums):
     3          out.append(path.copy())
     4          return
     5      path.append(nums[i])  # choose
     6      subsets(nums, i + 1, path, out)  # take
     7      path.pop()  # un-choose
     8      subsets(nums, i + 1, path, out)  # skip
    
    out = []
    subsets([1, 2, 3], 0, [], out)
    print(out)
    
    one call = one block of the tree
    path = the choices on the way from the root to that block
  3. Choose and explore

    Line 5 chooses: path.append(1) puts 1 in path. Line 6 explores: one call further down. The same happens for 2 and 3. Now i equals len(nums), so every number is decided and line 3 saves a copy: [1, 2, 3] is found.

    subsets(i=0)  line 5  path.append(1)   path = [1]
                  line 6  call i=1
    subsets(i=1)  line 5  path.append(2)   path = [1, 2]
                  line 6  call i=2
    subsets(i=2)  line 5  path.append(3)   path = [1, 2, 3]
                  line 6  call i=3
    subsets(i=3)  line 2  3 == len(nums)
                  line 3  out.append(path.copy())
    out = [[1, 2, 3]]
  4. Un-choose, then skip

    The leaf returns to the call for 3. Line 7 un-chooses: path.pop() removes 3, so path is [1, 2] again. Line 8 explores the skip branch with that same list and saves [1, 2]. Undoing each choice lets one list serve every branch.

    subsets(i=3)  line 4  return
    subsets(i=2)  line 7  path.pop()       path = [1, 2]
                  line 8  call i=3 (skip 3)
    subsets(i=3)  line 3  out.append(path.copy())
    out = [[1, 2, 3], [1, 2]]
    
    copy, not path itself: path keeps changing,
    a saved copy does not
  5. The whole walk

    Run it to the end. The puck goes depth first: the take edge, back up, then the skip edge. It saves 8 subsets, [1,2,3], [1,2], [1,3], [1], [2,3], [2], [3], [], in 15 calls, with one three-cell list the whole time.

    calls: 15   (1 + 2 + 4 + 8)
    found: 8
    order:
      1. [1, 2, 3]
      2. [1, 2]
      3. [1, 3]
      4. [1]
      5. [2, 3]
      6. [2]
      7. [3]
      8. []
    
    take is tried before skip, so [1, 2, 3] comes first and [] last
  6. Cost: 2ⁿ leaves

    Each extra number doubles the leaves: n numbers give 2ⁿ subsets and 2ⁿ⁺¹ − 1 calls (15 here). Copying a leaf costs up to n steps, so the search is Θ(n·2ⁿ). For n = 20 that is 1,048,576 subsets.

     n    subsets 2ⁿ    calls 2ⁿ⁺¹ − 1
     1            2                3
     2            4                7
     3            8               15
     4           16               31
    10         1024             2047
    20      1048576          2097151
    
    items copied into out: n·2ⁿ⁻¹ (each number is in half the subsets)
    n = 3: 12 items
    total work Θ(n·2ⁿ)
  7. Permutations: order matters

    Now list every order of [1, 2, 3]. At each level, choose any number not yet in path. The root has 3 choices, then 2, then 1: 3 × 2 × 1 = 6 leaves. The pattern is the same: append, recurse, pop.

     1  def perms(nums, path, out):
     2      if len(path) == len(nums):
     3          out.append(path.copy())
     4          return
     5      for x in nums:
     6          if x not in path:
     7              path.append(x)  # choose
     8              perms(nums, path, out)  # explore
     9              path.pop()  # un-choose
    
    out = []
    perms([1, 2, 3], [], out)
    print(out)
    
    leaves: 3 × 2 × 1 = 3! = 6
  8. Walk the order tree

    Line 5 tries each number; line 6 skips any already in path. Each choice is appended, explored, then popped so the next number can take its place. Found: [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1], in 16 calls.

    calls: 16   (1 + 3 + 6 + 6)
    found: 6
    order:
      1. [1, 2, 3]
      2. [1, 3, 2]
      3. [2, 1, 3]
      4. [2, 3, 1]
      5. [3, 1, 2]
      6. [3, 2, 1]
    
    same order as itertools.permutations([1, 2, 3])
  9. Cost: n! leaves

    n numbers have n! orders: 3! = 6, but 10! = 3,628,800. Backtracking cannot shrink a list that long; it saves rebuilding path at every leaf. It shines when a rule can stop a branch early, the subject of N-queens and pruning.

     n          n!
     1             1
     2             2
     3             6
     4            24
     5           120
    10     3,628,800
    12   479,001,600
    
    calls = 1 + n + n(n−1) + … + n!  (16 for n = 3)
    at least n! calls: one per leaf

اختبار يتاح بعد الخطوة الأخيرة.