-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution31_NextPermutation_bruteforce.py
59 lines (33 loc) · 1.24 KB
/
Solution31_NextPermutation_bruteforce.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import heapq
class Solution31_NextPermutation_bruteforce:
def nextPermutation(self, nums):
'''
Time : O (N!)
Space: O (N)
'''
def backtrack(first = 0):
'''
Permutation-generating recursive function
'''
if first == len(nums):
permutations.append(nums[:])
for i in range(first, len(nums)):
# 快捷写法
nums[first], nums[i] = nums[i], nums[first]
backtrack(first + 1)
# 快捷写法
nums[first], nums[i] = nums[i], nums[first]
# Generate all permutations from 'nums'
permutations = []
backtrack()
# Build a Min-Heap based on permutation already generated
heapq.heapify(permutations)
# In case 'nums' is the last permutation, return first permutation
if nums == permutations[-1]:
return permutations[0]
# Otherwise finds and returns next permutation
while heapq:
permutation = heapq.heappop(permutations)
if nums == permutation:
next_permutation = heapq.heappop(permutations)
return next_permutation