mirror of
https://github.com/dholerobin/Lecture_Notes.git
synced 2025-03-15 13:49:59 +00:00
Fix code indentation
This commit is contained in:
parent
1eaa3c0de9
commit
eb1c9f64af
@ -14,31 +14,31 @@ output: 2
|
||||
|
||||
```python
|
||||
def check(a, b):
|
||||
sq = int((a + b) ** 0.5)
|
||||
return (sq * sq) == (a + b)
|
||||
sq = int((a + b) ** 0.5)
|
||||
return (sq * sq) == (a + b)
|
||||
|
||||
if len(A) == 1: # corner case
|
||||
return int(check(A[0], 0))
|
||||
if len(A) == 1: # corner case
|
||||
return int(check(A[0], 0))
|
||||
|
||||
count = 0
|
||||
def permute_distinct(S, i):
|
||||
global count
|
||||
if i == len(S):
|
||||
count += 1
|
||||
global count
|
||||
if i == len(S):
|
||||
count += 1
|
||||
|
||||
for j in range(i, len(S)):
|
||||
if S[j] in S[i:j]: # prevent duplicates
|
||||
continue
|
||||
for j in range(i, len(S)):
|
||||
if S[j] in S[i:j]: # prevent duplicates
|
||||
continue
|
||||
|
||||
if i > 0 and (not check(S[j], S[i-1])): # invalid solution - branch and bound
|
||||
continue
|
||||
if i > 0 and (not check(S[j], S[i-1])): # invalid solution - branch and bound
|
||||
continue
|
||||
|
||||
S[i], S[j] = S[j], S[i]
|
||||
permute_distinct(S, i+1)
|
||||
S[i], S[j] = S[j], S[i]
|
||||
permute_distinct(S, i+1)
|
||||
|
||||
S[i], S[j] = S[j], S[i] # backtrack
|
||||
permute_distinct(A, 0)
|
||||
return count
|
||||
S[i], S[j] = S[j], S[i] # backtrack
|
||||
permute_distinct(A, 0)
|
||||
return count
|
||||
```
|
||||
|
||||
Gray Code
|
||||
@ -67,11 +67,11 @@ Example G(2) to G(3):
|
||||
```
|
||||
```python
|
||||
def gray(self, n):
|
||||
codes = [0, 1] # length 1
|
||||
for i in range(1, n):
|
||||
new_codes = [s | (1 << i) for s in reversed(codes)]
|
||||
codes += new_codes
|
||||
return codes
|
||||
codes = [0, 1] # length 1
|
||||
for i in range(1, n):
|
||||
new_codes = [s | (1 << i) for s in reversed(codes)]
|
||||
codes += new_codes
|
||||
return codes
|
||||
```
|
||||
|
||||
N Queens
|
||||
@ -92,20 +92,18 @@ B = ["cat", "cats", "and", "sand", "dog"]
|
||||
|
||||
Output 1:
|
||||
["cat sand dog", "cats and dog"]
|
||||
```
|
||||
```python
|
||||
def wordBreak(A, B):
|
||||
B = set(B)
|
||||
sents = []
|
||||
def foo(i, start, sent):
|
||||
word = A[start:i+1]
|
||||
if i == len(A):
|
||||
if word in B:
|
||||
sents.append((sent + ' ' + word).strip())
|
||||
return
|
||||
|
||||
if word in B:
|
||||
foo(i+1, i+1, sent + ' ' + word)
|
||||
foo(i+1, start, sent)
|
||||
foo(0, 0, '')
|
||||
B = set(B)
|
||||
sents = []
|
||||
def foo(i, start, sent):
|
||||
word = A[start:i+1]
|
||||
if i == len(A):
|
||||
if word in B:
|
||||
sents.append((sent + ' ' + word).strip())
|
||||
return
|
||||
if word in B:
|
||||
foo(i+1, i+1, sent + ' ' + word)
|
||||
foo(i+1, start, sent)
|
||||
foo(0, 0, '')
|
||||
```
|
Loading…
x
Reference in New Issue
Block a user