Skip to content

Commit ff4e184

Browse files
author
weng
committed
add 3 new problems
1 parent e4e4fc4 commit ff4e184

9 files changed

+202
-13
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
.DS_Store
22
.xlsx
3+
.pyc
34
*.*~
45
_*_.*
56

candy.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
11
#!/usr/bin/env python
22
'''
3-
Leetcode:
4-
There are N children standing in a line. Each child is assigned a rating value.
3+
Leetcode: Candy
54
5+
There are N children standing in a line. Each child is assigned a rating value.
66
You are giving candies to these children subjected to the following requirements:
7+
Each child must have at least one candy.
8+
Children with a higher rating get more candies than their neighbors.
79
8-
Each child must have at least one candy.
9-
Children with a higher rating get more candies than their neighbors.
1010
What is the minimum candies you must give?
11-
1211
'''
1312
from __future__ import division
1413
import random

copy_list_random_pointer.py

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
#!/usr/bin/env python
2+
'''
3+
Leetcode: Copy List with Random Pointer
4+
A linked list is given such that each node contains an additional random pointer
5+
which could point to any node in the list or null. Return a deep copy of the list.
6+
'''
7+
8+
from __future__ import division
9+
import random
10+
import LinkedList
11+
12+
13+
class Node(LinkedList.Node):
14+
def __init__(self, value, next=None, prev=None, randp=None):
15+
super(Node, self).__init__(value, next, prev)
16+
self.randp = randp
17+
def __str__(self):
18+
if self.randp is None: s = '[%d]' % self.value
19+
else: s = '[%d,%d]' % (self.value, self.randp.value)
20+
if self.next:
21+
s += '->(%s)' % str(self.next)
22+
return s
23+
24+
# Brute-force
25+
# create the list first and then set up the pointer
26+
def copylist(head):
27+
new_head = Node(head.value)
28+
# Copy the list
29+
prev_n = new_head
30+
node = head.next
31+
while node:
32+
n = Node(node.value)
33+
prev_n.next = n
34+
prev_n = n
35+
node = node.next
36+
37+
# Assign pointer
38+
node = head
39+
new_node = new_head
40+
while node:
41+
if node.randp:
42+
# locate the pointer
43+
h = head
44+
newh = new_head
45+
while h != node.randp:
46+
h = h.next
47+
newh = newh.next
48+
new_node.randp = newh
49+
node = node.next
50+
new_node = new_node.next
51+
print 'Orig:', head
52+
print 'Copy:', new_head
53+
54+
55+
if __name__ == '__main__':
56+
n6 = Node(6)
57+
n5 = Node(5, n6)
58+
n4 = Node(4, n5)
59+
n3 = Node(3, n4)
60+
n2 = Node(2, n3)
61+
n1 = Node(1, n2)
62+
n1.randp = n4
63+
n2.randp = n4
64+
n4.randp = n6
65+
n5.randp = n3
66+
67+
copylist(n1)
68+
69+

gas_station.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,12 @@
11
#!/usr/bin/env python
22
'''
3-
Leetcode:
4-
There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
3+
Leetcode: Gas Station
54
5+
There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
66
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
7-
87
Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.
98
10-
Note:
11-
The solution is guaranteed to be unique.
12-
9+
Note: The solution is guaranteed to be unique.
1310
'''
1411
from __future__ import division
1512
import random
@@ -18,8 +15,9 @@
1815
# the car can use gas at i-th but not at j-th
1916
# only valid when G(i,j) >= 0
2017
# G(i,j) = max{G(i,mid)+G(k,mid) for i < mid < j,
21-
# gas[i] - cost[i]+...+cost[j]}
18+
# gas[i] - (cost[i]+...+cost[j])}
2219
# We use G(i,i) for a circular route.
20+
# ~ O(n^2)
2321
def gas_station(gas, cost):
2422
n = len(gas)
2523
G = {}

letter_comb_phone.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ def phone_mapping2(num2lett, dictionary, number, words):
5959

6060
if len(number) == 0: return True
6161

62-
if number in memo and not memo[number]: return False
62+
if number in memo: return memo[number]
6363

6464
n = len(number)
6565
can_split = False

next_permutation.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ def iter_permutation(L):
5555
print L
5656
while True:
5757
i = n - 2
58+
# Find i-th element that < right element
5859
while i >= 0:
5960
if L[i] < L[i+1]: break
6061
i -=1

single_number.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#!/usr/bin/env python
2+
3+
from __future__ import division
4+
import random
5+
6+
'''
7+
Leetcode: Single Number
8+
9+
Given an array of integers, every element appears twice except for one. Find that single one.
10+
Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
11+
'''
12+
def func():
13+
pass
14+
15+
16+
'''
17+
Leetcode: Single Number II
18+
19+
Given an array of integers, every element appears three times except for one. Find that single one.
20+
Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
21+
22+
23+
'''
24+
def func():
25+
pass
26+
27+
28+
if __name__ == '__main__':
29+
func()
30+
31+

valid_palin.pyc

-10.1 KB
Binary file not shown.

word_break.py

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
#!/usr/bin/env python
2+
'''
3+
http://thenoisychannel.com/2011/08/08/retiring-a-great-interview-problem/
4+
'''
5+
from __future__ import division
6+
import random
7+
8+
9+
'''
10+
Leetcode: Word Break
11+
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
12+
For example, given
13+
s = "leetcode",
14+
dict = ["leet", "code"].
15+
Return true because "leetcode" can be segmented as "leet code".
16+
'''
17+
def wordbreak(s, words):
18+
if len(s) == 0: return True
19+
# Test all prefixes
20+
for i in range(1, len(s)+1):
21+
sub = s[:i]
22+
if not sub in words: continue
23+
if wordbreak(s[i:], words):
24+
return True
25+
return False
26+
27+
28+
### DP? O(n^2)
29+
# cut(i) = s[:i] can be splitted
30+
# cut(i+1) = OR{cut(j) and s[j:i] is a word for 0 <= j < i}
31+
def wordbreak_DP(s, words):
32+
words = set(words)
33+
cut = {0: True}
34+
for i in range(1,len(s)+1):
35+
cut[i] = False
36+
for j in range(i):
37+
if cut[j] and s[j:i] in words:
38+
cut[i] = True
39+
break
40+
return cut[len(s)]
41+
42+
43+
memo = {}
44+
def wordbreak_memo(s, words):
45+
if s == '': return True
46+
global memo
47+
if s in memo: return memo[s]
48+
for i in range(1,len(s)+1):
49+
sub = s[:i]
50+
if not sub in words: continue
51+
if wordbreak_memo(s[i:], words):
52+
memo[s] = True#; print memo
53+
return True
54+
return False
55+
56+
'''
57+
Leetcode: Word Break II
58+
Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.
59+
For example, given
60+
s = "catsanddog",
61+
dict = ["cat", "cats", "and", "sand", "dog"].
62+
A solution is ["cats and dog", "cat sand dog"].
63+
'''
64+
# ~O(exponential)
65+
def wordbreak2_generator(s, words):
66+
if len(s) == 0: yield []
67+
else:
68+
# Test all prefixes
69+
for i in range(1, len(s)+1):
70+
sub = s[:i]
71+
if not sub in words: continue
72+
for others in wordbreak2_generator(s[i:], words):
73+
yield [sub] + others
74+
75+
def wordbreak2(s, words):
76+
words = set(words)
77+
for combo in wordbreak2_generator(s, words):
78+
print combo
79+
80+
81+
82+
if __name__ == '__main__':
83+
s = "catsanddogseat"
84+
words = set(["cat", "cats", "and", "sand", "dog", "dogs", "eat", "seat"])
85+
print wordbreak(s, words)
86+
print wordbreak_DP(s, words)
87+
print wordbreak_memo(s, words)
88+
wordbreak2(s, words)
89+
90+

0 commit comments

Comments
 (0)