Skip to content

Commit

Permalink
1031-20/10
Browse files Browse the repository at this point in the history
  • Loading branch information
youhusky committed Nov 1, 2017
1 parent 5676839 commit 108df83
Show file tree
Hide file tree
Showing 2 changed files with 94 additions and 0 deletions.
44 changes: 44 additions & 0 deletions 017. Letter Combinations of a Phone Number.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# Given a digit string, return all possible letter combinations that the number could represent.

# A mapping of digit to letters (just like on the telephone buttons) is given below.



# Input:Digit string "23"
# Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

# DFS backtracking
class Solution(object):
def letterCombinations(self, digits):
"""
O(2^n)
:type digits: str
:rtype: List[str]
"""
if not digits:
return []
res = []
dic = {
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz'
}
self.dfs(res, '',dic,digits,0)
return res

def dfs(self, res, temp, dic,digits,num):
if num == len(digits):
res.append(temp)
return

# focus on !
for letter in dic[digits[num]]:
self.dfs(res, temp+letter, dic, digits, num+1)



50 changes: 50 additions & 0 deletions 173. Binary Search Tree Iterator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.

# Calling next() will return the next smallest number in the BST.

# Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.

# Credits:
# Special thanks to @ts for adding this problem and creating all test cases.

# Definition for a binary tree node
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class BSTIterator(object):
def __init__(self, root):
"""
:type root: TreeNode
"""
self.stack = []
self.push(root)


def hasNext(self):
"""
:rtype: bool
"""
return True if self.stack else False


def next(self):
"""
:rtype: int
"""
node = self.stack.pop()
self.push(node.right)
return node.val

def push(self,node):
while node:
# imp
self.stack.append(node)
node = node.left


# Your BSTIterator will be called like this:
# i, v = BSTIterator(root), []
# while i.hasNext(): v.append(i.next())

0 comments on commit 108df83

Please sign in to comment.