-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpermutations.py
78 lines (68 loc) · 1.64 KB
/
permutations.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# -----------------------------------------------
# Author : Mohit Chaudhari
# Created Date : 22/08/21
# -----------------------------------------------
# ***** Permutations *****
# Problem Description
#
# Given an integer array A of size N denoting collection of numbers , return all possible permutations.
#
# NOTE:
#
# No two entries in the permutation sequence should be the same.
# For the purpose of this problem, assume that all the numbers in the collection are unique.
# Return the answer in any order
# WARNING: DO NOT USE LIBRARY FUNCTION FOR GENERATING PERMUTATIONS.
# Example : next_permutations in C++ / itertools.permutations in python.
# If you do, we will disqualify your submission retroactively and give you penalty points.
#
#
# Problem Constraints
# 1 <= N <= 9
#
#
#
# Input Format
# Only argument is an integer array A of size N.
#
#
#
# Output Format
# Return a 2-D array denoting all possible permutation of the array.
#
#
#
# Example Input
# A = [1, 2, 3]
#
#
# Example Output
# [ [1, 2, 3]
# [1, 3, 2]
# [2, 1, 3]
# [2, 3, 1]
# [3, 1, 2]
# [3, 2, 1] ]
#
#
# Example Explanation
# All the possible permutation of array [1, 2, 3].
import are as are
class Solution:
# @param A : list of integers
# @return a list of list of integers
def permute(self, A):
result = list()
if len(A) == 1:
return [A[:]]
for i in range(len(A)):
n = A.pop(0)
perms = self.permute(A)
for perm in perms:
perm.append(n)
result.extend(perms)
A.append(n)
return result
s = Solution()
print(s.permute([1, 2, 3]))
# OUTPUT: