Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e7111f8

Browse files
added permutations and combination problems
1 parent 72d7625 commit e7111f8

File tree

9 files changed

+263
-0
lines changed

9 files changed

+263
-0
lines changed

‎Hard/PermutationSequence/README.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Permutation Sequence
2+
3+
[Leetcode Link](#)
4+
5+
## Problem:
6+
7+
The set `[1, 2, 3, ..., n]` contains a total of n! unique permutations.
8+
9+
By listing and labeling all of the permutations in order, we get the following sequence for `n = 3`:
10+
11+
1. `"123"`
12+
2. `"132"`
13+
3. `"213"`
14+
4. `"231"`
15+
5. `"312"`
16+
6. `"321"`
17+
Given `n` and `k`, return the `k`\_th permutation sequence.
18+
19+
## Example:
20+
21+
```
22+
Input: n = 3, k = 3
23+
Output: "213"
24+
```
25+
26+
```
27+
Input: n = 4, k = 9
28+
Output: "2314"
29+
```
30+
31+
```
32+
Input: n = 3, k = 1
33+
Output: "123"
34+
```
35+
36+
## Note:
37+
38+
- `1 <= n <= 9`
39+
- `1 <= k <= n!`

‎Hard/PermutationSequence/solution.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import math
2+
3+
4+
class Solution:
5+
# brute force, find all permutations and return the k-th permutation (slow, LC submission time limit exceed)
6+
def getPermutation(self, n: int, k: int) -> str:
7+
def permute_rec(nums, start):
8+
if start >= len(nums):
9+
stringFormat = ""
10+
for num in nums:
11+
stringFormat += str(num)
12+
allPermutations.append(stringFormat)
13+
14+
for i in range(start, len(nums)):
15+
nums[start], nums[i] = nums[i], nums[start]
16+
permute_rec(nums, start+1)
17+
nums[start], nums[i] = nums[i], nums[start]
18+
19+
nums = [n+1 for n in range(n)]
20+
allPermutations = list()
21+
permute_rec(nums, 0)
22+
allPermutations.sort()
23+
return allPermutations[k-1]
24+
25+
# smarter way from LC discuss (using mathematics)
26+
"""
27+
One main thing to consider is that when you have a five digit number possible numbers are 1,2,3,4,5.
28+
So the number of permutations that start with 1 are (5-1)! = 4!
29+
Similarly with 2 and 3 and 4 and 5.
30+
So if the k = 32 it means that i need to cross all the possibilites with 1 which are 24. and then check in the possibilties that start with 2. now we have crossed 24 possibilties so 32-24=8 are remaining.
31+
Now repeat the whole process with second significant digit.
32+
"""
33+
34+
def getPermutation_smart(self, n: int, k: int) -> str:
35+
nums = [n+1 for n in range(n)]
36+
answer = ""
37+
while nums:
38+
fact = len(nums)-1
39+
numPermEach = math.factorial(fact)
40+
indexOfNumToAppend = k // numPermEach
41+
if k % numPermEach == 0:
42+
indexOfNumToAppend -= 1
43+
answer += str(nums[indexOfNumToAppend])
44+
nums.pop(indexOfNumToAppend)
45+
k -= indexOfNumToAppend * numPermEach
46+
return answer
47+
48+
49+
sol = Solution()
50+
n = 3
51+
k = 4
52+
print(sol.getPermutation_smart(n, k))

‎Medium/Combinations/README.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Combinations
2+
3+
[Leetcode Link](https://leetcode.com/problems/combinations/)
4+
5+
## Problem:
6+
7+
Given two integers **n** and **k**, return all possible combinations of **k** numbers out of 1 ... n.
8+
9+
You may return the answer _in any order_.
10+
11+
## Example:
12+
13+
```
14+
Input: n = 4, k = 2
15+
Output:
16+
[
17+
[2,4],
18+
[3,4],
19+
[2,3],
20+
[1,2],
21+
[1,3],
22+
[1,4],
23+
]
24+
```
25+
26+
```
27+
Input: n = 1, k = 1
28+
Output: [[1]]
29+
```
30+
31+
## Note:

‎Medium/Combinations/solution.py

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+
def combine(self, n: int, k: int) -> List[List[int]]:
6+
def combinations(nums, combination):
7+
if len(combination) == k:
8+
result.append(list(combination))
9+
return
10+
11+
for i in range(len(nums)):
12+
combination.append(nums[i])
13+
combinations(nums[i+1:], combination)
14+
combination.pop()
15+
16+
result = list()
17+
combinations([num+1 for num in range(n)], [])
18+
return result
19+
20+
21+
sol = Solution()
22+
n = 5
23+
k = 3
24+
print(sol.combine(n, k))

‎Medium/Permutations/README.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Permutations
2+
3+
[Leetcode Link](https://leetcode.com/problems/permutations/)
4+
5+
## Problem:
6+
7+
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in _any order_.
8+
9+
## Example:
10+
11+
```
12+
Input: nums = [1,2,3]
13+
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
14+
```
15+
16+
```
17+
Input: nums = [0,1]
18+
Output: [[0,1],[1,0]]
19+
```
20+
21+
```
22+
Input: nums = [1]
23+
Output: [[1]]
24+
```
25+
26+
## Note:
27+
28+
- 1 <= nums.length <= 6
29+
- -10 <= nums[i] <= 10
30+
- All the integers of nums are _unique_.

‎Medium/Permutations/solution.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def permute(self, nums: List[int]) -> List[List[int]]:
6+
def permute_rec(nums, start):
7+
if start >= len(nums):
8+
allPermutations.append(list(nums))
9+
return
10+
for i in range(start, len(nums)):
11+
nums[start], nums[i] = nums[i], nums[start]
12+
permute_rec(nums, start+1)
13+
nums[start], nums[i] = nums[i], nums[start]
14+
15+
allPermutations = list()
16+
permute_rec(nums, 0)
17+
return allPermutations
18+
19+
20+
sol = Solution()
21+
nums = [1, 2, 3]
22+
print(sol.permute(nums))

‎Medium/Permutations2/README.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Permutations II
2+
3+
[Leetcode Link](https://leetcode.com/problems/permutations-ii/)
4+
5+
## Problem:
6+
7+
Given a collection of numbers, `nums`, that might contain duplicates, return all possible unique permutations _in any order_.
8+
9+
## Example:
10+
11+
```
12+
Input: nums = [1,1,2]
13+
Output:
14+
[[1,1,2],
15+
[1,2,1],
16+
[2,1,1]]
17+
```
18+
19+
```
20+
Input: nums = [1,2,3]
21+
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
22+
```
23+
24+
## Note:
25+
26+
- 1 <= nums.length <= 8
27+
- -10 <= nums[i] <= 10

‎Medium/Permutations2/solution.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
from typing import List
2+
from collections import defaultdict
3+
4+
5+
class Solution:
6+
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
7+
def permute_rec(freqDict: defaultdict, permutation: List[int]):
8+
remSum = 0
9+
for count in freqDict.values():
10+
remSum += count
11+
if remSum <= 0:
12+
result.append(list(permutation))
13+
return
14+
15+
for num, count in freqDict.items():
16+
if count > 0:
17+
freqDict[num] -= 1
18+
permutation.append(num)
19+
permute_rec(freqDict, permutation)
20+
permutation.pop()
21+
freqDict[num] += 1
22+
23+
result = list()
24+
freqDict = defaultdict(int)
25+
for num in nums:
26+
freqDict[num] += 1
27+
print(freqDict)
28+
permute_rec(freqDict, [])
29+
return result
30+
31+
32+
sol = Solution()
33+
nums = [1, 1, 2]
34+
print(sol.permuteUnique(nums))

‎README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,9 @@ Languages used: Java and Python
9393
- [Binary Tree Postorder Traversal](Medium/BinaryPostorder)
9494
- [Reconstruct Itinerary](Medium/ReconstructItinerary)
9595
- [Course Schedule II](Medium/CourseSchedule2)
96+
- [Permutations](Medium/Permutations)
97+
- [Permutations II](Medium/Permutations2)
98+
- [Combinations](Medium/Combinations)
9699
- Hard
97100

98101
- [Maximum Score Words Formed by Letters](Hard/MaximumScoreWords)
@@ -103,6 +106,7 @@ Languages used: Java and Python
103106
- [Find Median From Data Stream](Hard/FindMedianFromDataStream)
104107
- [Escape a Large Maze](Hard/EscapeLargeMaze)
105108
- [Serialize and Deserialize Binary Tree](Hard/SerializeAndDeserializeBinaryTree)
109+
- [Permutation Sequence](Hard/PermutationSequence)
106110

107111
- Others (Non-leetcode)
108112
- [Check Valid Tree Given Edges](Others/CheckValidTreeGivenEdges)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /