BackTracking

重点在于如何构建logic tree

构建logic tree, 方便推算Time complexity https://www.1point3acres.com/bbs/thread-583166-1-1.html

好题

  • permutations II

  • subset II

  • 区分combination-->permutation-->subset不同的出口

  • subset是combination的一种

    • combination[1,2,3]和[3,2,1]是一样的,所以需要startIdx来track

    • permutation中[1,2,3]和[3,2,1]不一样,所以always start from 0

  • Generate parentheses

  • Generalized Abbreviation

  • N queens

  • Word search ---不能死套模板

Permutation类的题目

  • generate all permutations ----> permutations

  • next permutation

  • generate the permutation number K ----> permutation sequence

建立一个visited[] 来记录每个nums[i]是否被用过

  • 去重的题一般都需要先sort array, 然后再check duplicate

  • if (i > 0 && nums[i] == nums[i - 1] && !visited[i-1]) continue;

Permutation Sequence

  • 不适合做面试题

  • 康托展开的应用

  • 如n=5,x=96时:

    • 首先用96-1得到95,说明x之前有95个排列.(将此数本身减去1)

    • 用95去除4! 得到3余23,说明有3个数比第1位小,所以第一位是4.

    • 用23去除3! 得到3余5,说明有3个数比第2位小,所以是4,但是4已出现过,因此是5.

    • 用5去除2!得到2余1,类似地,这一位是3.

    • 用1去除1!得到1余0,这一位是2. 最后一位只能是1.

    • 所以这个数是45321. 按以上方法可以得出通用的算法。

  • 给定n和k, 从1~n中选K个数,返回所有结果

Combination Sum组合题

Combination sum I

  • no duplicate num

  • same num can be chosen unlimited times

  • 可选可不选就是for loop to iterate each element as starting index

Combination sum II

  • dup num

  • each num can only be used once

  • Combination sum III

    • 1-9里选K个数sum to N

  • Combination Sum IV

    • all positive numbers, no dup

    • find num of combinations that sum to target

    • DP

N Queens

  • 先想high level的框架,如何能套用dfs模板,不用着急去实现drawBoard()

  • 想清楚isValid() logic

  • 九章模板清晰好用!

  • backtracking必练题

  • 需要灵活套用backtracking模板

  • 想清楚递归三要素

  • 如何定义for loop, 如何定义递归函数

枚举 Generate Parentheses

  • helper(List res, StringBuilder sb, int left, int right, int n)

  • left tracks number of '(' has been placed

  • right tracks number of ') hash been placed

  • when to consider place another '(' --> when left < n

  • when to consider place another ')' --> when left > right

Generalized Abbreviation

  • 典型的backtracking题

  • 切记任何时候调用sb.append()完都需要sb.setLength(len), 尤其是递归的出口add result的时候

  • 如果是直接res.add(sb.toString()), 没有任何sb.append()操作的话可以 early return

Last updated

Was this helpful?