Code Interview Note
  • 0. Introduction
  • 1. Basic
    • Python Basic
    • Java Basic
    • Primitive Type
    • Basic Question
    • Number
  • 2. Array and Numbers
    • General
    • TwoSum
    • Buy and Sell Stock
    • SubArray
      • SubArray + HashMap
    • Sliding Window
      • Sliding Window At Most Problem
    • Word Break
    • Passes Problem
    • Majority Element
    • Partition Array
    • Sort Colors
    • Anagram
    • Ugly Number
    • TwoPointer
    • Swipe Line
    • Calculator
    • Sudoku
  • 2.1 String
    • String
    • Palindrome
    • Parentheses
    • Decode String
    • Calculator
    • Abbreviation
  • 3. Linkedlist
    • Dummy Node
    • Double Pointers
  • 4. Stack and Queue
    • General
    • Increase/Decrease Stack
  • 5. Binary Search
    • General
    • BS on result
    • Save the half which has result
    • Rotated Sorted Array
    • Split Array Largest Sum
  • 6. Binary Tree
    • General
    • Path Sum
    • Lowest Common Ancestor
    • BST
    • Convert
    • Traverse
    • Valid Ordered Tree
    • Construct Binary Tree
    • Tree depth and width
    • Vertical Order Traverse
  • 7. Heap
    • Geneal
    • TopK
  • 8. Simulation
    • General
    • Read4
    • Encode Decode
    • LRU/LFU
    • Robot
    • GetRandom O(1)
    • Probability
  • 9. DFS
    • Backtrack
    • General
    • Subset
    • Permutation
    • Combination
  • 10. HashTable
    • General
  • 11. Sort
    • General
  • 12. Recursion
    • General
  • 13. Dynamic Programming
    • Graph
    • General
    • Coordinate
    • Double Sequence
    • Longest Common Subsequence
    • Rolling Array
    • House Robber
    • Backpack
    • Memorization
    • Diagonal
  • 14. BFS
    • General
    • Number of Islands
    • The Maze
  • 15. Graph
    • Shortest Path
    • Undirected Graph
    • Topology Sort
    • Word Ladder
    • Tarjan's Algo
  • 16. Divide & Conquer
    • General
  • 17. UnionFind
    • General
    • Grouping
  • 18. Trie
    • General
    • Word Square
  • 19. Company Summary
    • Oracle
    • Amazon
      • DP
    • Google
    • Hackerrank
    • LinkedIn
  • 20. Design
  • 21. Math
  • Behavior Question
  • Internet
  • OS
Powered by GitBook
On this page
  • 282. Expression Add Operator
  • 351. Android Unlock Pattern

Was this helpful?

  1. 9. DFS

Backtrack

282. Expression Add Operator

Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value.

Example 1:

Input: num = "123", target = 6
Output: ["1+2+3", "1*2*3"] 
  • 4 Operations: number extension, add, minus, multiple

  • Record pre number for multiple operator to rollback

  • First position only valid for add operator

  • Number init with '0' is invalid

def addOperators(self, num: str, target: int) -> List[str]:
    self.ans = []
    self.backtrack(num, '', target, 0, 0, 0)
    return self.ans


def backtrack(self, num, express, target, idx, cur, pre):
    if idx == len(num):

        if cur == target:
            self.ans.append(express)
        return

    for end in range(idx+1, len(num)+1):
        # 01 is invalid
        if num[idx] == '0' and end > idx+1: break
        n = int(num[idx:end])

        # first index just has positive number
        if idx == 0:
            self.backtrack(num, str(n), target, end, n, n)
        else:
            self.backtrack(num, express+'+'+str(n), target, end, cur+n, n)
            self.backtrack(num, express+'-'+str(n), target, end, cur-n, -n)
            self.backtrack(num, express+'*'+str(n), target, end, cur-pre+n*pre, n*pre)

351. Android Unlock Pattern

  1. add count by DFS

  2. Build a skip matrix

  3. Only not visit and (skip[i][j]==0 or visit[skip[i][j]] has visit, then go in recursion

def numberOfPatterns(self, m: int, n: int) -> int:
    self.skip = [[0] *10 for _ in range(10)]
    self.skip[1][3] = self.skip[3][1] = 2
    self.skip[1][7] = self.skip[7][1] = 4
    self.skip[3][9] = self.skip[9][3] = 6
    self.skip[7][9] = self.skip[9][7] = 8
    self.skip[1][9] = self.skip[9][1] = self.skip[3][7] = self.skip[7][3] = \
    self.skip[2][8] = self.skip[8][2] = self.skip[4][6] = self.skip[6][4] = 5
    
    res = 0
    visit = [False] * 10
    for i in range(m, n+1):
        res += self.dfs(visit, 1, i-1) * 4  # 1, 3, 7, 9 are symmetric
        res += self.dfs(visit, 2, i-1) * 4  # 2, 4, 6, 8 are symmetric
        res += self.dfs(visit, 5, i-1)    
    return res

def dfs(self, visit, p, remain):
    if remain == 0: return 1
    visit[p] = True
    res = 0
    for i in range(1, 10):
        if not visit[i] and (self.skip[p][i] == 0 or visit[self.skip[p][i]] == True):
            res += self.dfs(visit, i, remain-1)

    visit[p] = False
    return res

Previous9. DFSNextGeneral

Last updated 4 years ago

Was this helpful?

Problem