Skip to content

Commit 93abe50

Browse files
committed
D. J.:
- Added the leetcode problem and solution for 22, 39, 51 and 52
1 parent e74fca3 commit 93abe50

9 files changed

+206
-0
lines changed

README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,18 +38,22 @@ This repository contains awesome LeetCode problems and solutions written in Pyth
3838
- [19 Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/)
3939
- [20 Valid Parentheses](https://leetcode.com/problems/valid-parentheses/description/)
4040
- [21 Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/description/)
41+
- [22 Generate Parentheses](https://leetcode.com/problems/generate-parentheses/description/)
4142
- [25 Reverse Nodes in k-Group](https://leetcode.com/problems/reverse-nodes-in-k-group/description/)
4243
- [26 Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/)
4344
- [27 Remove Element](https://leetcode.com/problems/remove-element/description/)
4445
- [28 Find the Index of the First Occurrence in a String](https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/description/)
4546
- [30 Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words/description/)
4647
- [36 Valid Sudoku](https://leetcode.com/problems/valid-sudoku/description/)
48+
- [39 Combination Sum](https://leetcode.com/problems/combination-sum/description/)
4749
- [42 Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/description/)
4850
- [45 Jump Game II](https://leetcode.com/problems/jump-game-ii/description/)
4951
- [46 Permutations](https://leetcode.com/problems/permutations/description/)
5052
- [48 Rotate Image](https://leetcode.com/problems/rotate-image/description/)
5153
- [49 Group Anagrams](https://leetcode.com/problems/group-anagrams/description/)
5254
- [50 Pow(x_n)](https://leetcode.com/problems/powx-n/description/)
55+
- [51 N-Queens](https://leetcode.com/problems/n-queens/description/)
56+
- [52 N-Queens II](https://leetcode.com/problems/n-queens-ii/description/)
5357
- [54 Spiral Matrix](https://leetcode.com/problems/spiral-matrix/description/)
5458
- [55 Jump Game](https://leetcode.com/problems/jump-game/description/)
5559
- [58 Length of Last Word](https://leetcode.com/problems/length-of-last-word/description/)
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
"""Base class for all LeetCode Problems."""
6+
7+
def generateParenthesis(self, n: int) -> List[str]:
8+
"""
9+
Given n pairs of parentheses, write a function to generate all combinations of
10+
well-formed parentheses.
11+
"""
12+
res = []
13+
14+
def dfs(p: str, openP: int, endP: int):
15+
if openP == n and endP == n:
16+
res.append(p)
17+
return
18+
if openP < n:
19+
dfs(p + "(", openP + 1, endP)
20+
if openP > endP and endP < n:
21+
dfs(p + ")", openP, endP + 1)
22+
23+
dfs("", 0, 0)
24+
return res
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
"""Base class for all LeetCode Problems."""
6+
7+
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
8+
"""
9+
Given an array of distinct integers candidates and a target integer target,
10+
return a list of all unique combinations of candidates where the chosen numbers
11+
sum to target. You may return the combinations in any order.
12+
13+
The same number may be chosen from candidates an unlimited number of times. Two
14+
combinations are unique if the frequency of at least one of the chosen numbers
15+
is different.
16+
17+
The test cases are generated such that the number of unique combinations that
18+
sum up to target is less than 150 combinations for the given input.
19+
"""
20+
res = []
21+
22+
def dfs(i: int, pair: List[int], total: int):
23+
if total == target:
24+
res.append(pair.copy())
25+
return
26+
if i >= len(candidates) or total > target:
27+
return
28+
29+
pair.append(candidates[i])
30+
dfs(i, pair, total + candidates[i])
31+
pair.pop()
32+
dfs(i + 1, pair, total)
33+
34+
dfs(0, [], 0)
35+
return res
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
"""Base class for all LeetCode Problems."""
6+
7+
def solveNQueens(self, n: int) -> List[List[str]]:
8+
"""
9+
The n-queens puzzle is the problem of placing n queens on an n x n chessboard
10+
such that no two queens attack each other.
11+
12+
Given an integer n, return all distinct solutions to the n-queens puzzle. You
13+
may return the answer in any order.
14+
15+
Each solution contains a distinct board configuration of the n-queens'
16+
placement, where 'Q' and '.' both indicate a queen and an empty space,
17+
respectively.
18+
"""
19+
res = []
20+
cols, diags, anti_diags = set(), set(), set()
21+
22+
def dfs(row: int, pairs: List[str]):
23+
if row == n:
24+
res.append(pairs.copy())
25+
return
26+
for col in range(n):
27+
if col in cols or (row + col) in diags or (row - col) in anti_diags:
28+
continue
29+
cols.add(col)
30+
diags.add(row + col)
31+
anti_diags.add(row - col)
32+
pairs.append(col * "." + "Q" + (n - col - 1) * ".")
33+
dfs(row + 1, pairs)
34+
pairs.pop()
35+
cols.remove(col)
36+
diags.remove(row + col)
37+
anti_diags.remove(row - col)
38+
39+
dfs(0, [])
40+
return res
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution:
2+
"""Base class for all LeetCode Problems."""
3+
4+
def totalNQueens(self, n: int) -> int:
5+
"""
6+
The n-queens puzzle is the problem of placing n queens on an n x n chessboard
7+
such that no two queens attack each other.
8+
9+
Given an integer n, return the number of distinct solutions to the n-queens
10+
puzzle.
11+
"""
12+
count = 0
13+
cols, diags, anti_diags = set(), set(), set()
14+
15+
def dfs(row: int):
16+
if row == n:
17+
nonlocal count
18+
count += 1
19+
return
20+
for col in range(n):
21+
if col in cols or (row + col) in diags or (row - col) in anti_diags:
22+
continue
23+
cols.add(col)
24+
diags.add(row + col)
25+
anti_diags.add(row - col)
26+
dfs(row + 1)
27+
cols.remove(col)
28+
diags.remove(row + col)
29+
anti_diags.remove(row - col)
30+
31+
dfs(0)
32+
return count

tests/test_22_generate_parentheses.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
from typing import List
2+
3+
import pytest
4+
5+
from awesome_python_leetcode._22_generate_parentheses import Solution
6+
7+
8+
@pytest.mark.parametrize(
9+
argnames=["n", "expected"],
10+
argvalues=[
11+
(3, ["((()))", "(()())", "(())()", "()(())", "()()()"]),
12+
(1, ["()"]),
13+
],
14+
)
15+
def test_func(n: int, expected: List[str]):
16+
"""Tests the solution of a LeetCode problem."""
17+
combinations = Solution().generateParenthesis(n)
18+
assert combinations == expected

tests/test_39_combination_sum.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
from typing import List
2+
3+
import pytest
4+
5+
from awesome_python_leetcode._39_combination_sum import Solution
6+
7+
8+
@pytest.mark.parametrize(
9+
argnames=["candidates", "target", "expected"],
10+
argvalues=[
11+
([2, 3, 6, 7], 7, [[2, 2, 3], [7]]),
12+
([2, 3, 5], 8, [[2, 2, 2, 2], [2, 3, 3], [3, 5]]),
13+
([2], 1, []),
14+
],
15+
)
16+
def test_func(candidates: List[int], target: int, expected: List[List[int]]):
17+
"""Tests the solution of a LeetCode problem."""
18+
combinations = Solution().combinationSum(candidates, target)
19+
assert combinations == expected

tests/test_51_n_queens.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
from typing import List
2+
3+
import pytest
4+
5+
from awesome_python_leetcode._51_n_queens import Solution
6+
7+
8+
@pytest.mark.parametrize(
9+
argnames=["n", "expected"],
10+
argvalues=[
11+
(4, [[".Q..", "...Q", "Q...", "..Q."], ["..Q.", "Q...", "...Q", ".Q.."]]),
12+
(1, [["Q"]]),
13+
],
14+
)
15+
def test_func(n: int, expected: List[List[str]]):
16+
"""Tests the solution of a LeetCode problem."""
17+
combinations = Solution().solveNQueens(n)
18+
assert combinations == expected

tests/test_52_n_queens_II.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import pytest
2+
3+
from awesome_python_leetcode._52_n_queens_II import Solution
4+
5+
6+
@pytest.mark.parametrize(
7+
argnames=["n", "expected"],
8+
argvalues=[
9+
(4, 2),
10+
(1, 1),
11+
],
12+
)
13+
def test_func(n: int, expected: int):
14+
"""Tests the solution of a LeetCode problem."""
15+
combinations = Solution().totalNQueens(n)
16+
assert combinations == expected

0 commit comments

Comments
 (0)