Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

理解backtracking #7

Open
y4h2 opened this issue Nov 24, 2022 · 2 comments
Open

理解backtracking #7

y4h2 opened this issue Nov 24, 2022 · 2 comments

Comments

@y4h2
Copy link
Owner

y4h2 commented Nov 24, 2022

backtracing的本质还是dfs

可以从常见的简单的dfs进行推导。

简单的dfs例子200. Number of Islands, 地图类的dfs的方案是从当前的点(i, j)向四周(i+1, j), (i-1, j), (i, j+1), (i, j-1)移动,对于下一个点一般会有条件约束,

而对于46. Permutations从当前点(i, j)向其他所有的点移动,限制是不能取重复的点

@y4h2
Copy link
Owner Author

y4h2 commented Nov 24, 2022

tree的遍历类似于dfs的特殊情况。preorder, inorder, postorder相当于对于stack进出栈的不同讨论。
tree是分别处理左右子树, backtrack是处理for循环

@y4h2
Copy link
Owner Author

y4h2 commented Nov 24, 2022

1079. Letter Tile Possibilities
通过Counter来避免生成重复值

class Solution:
    def numTilePossibilities(self, tiles: str) -> int:
        counter = Counter(tiles)
        self.result = 0
        
        def backtracking():
            self.result += 1
            for i in range(26):
                c = chr(ord('A') + i)
                if counter[c] == 0:
                    continue

                counter[c] -= 1

                backtracking()
                counter[c] += 1
                
        backtracking() 
        return self.result

也可以通过对字符串排序,然后控制index来避免重复

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant