Python3程序打印给定数组的所有可能旋转
给定一个大小为N的整数数组arr[] ,任务是打印数组所有可能的旋转。
例子:
Input: arr[] = {1, 2, 3, 4}
Output: {1, 2, 3, 4}, {4, 1, 2, 3}, {3, 4, 1, 2}, {2, 3, 4, 1}
Explaination:
Initial arr[] = {1, 2, 3, 4}
After first rotation arr[] = {4, 1, 2, 3}
After second rotation arr[] = {3, 4, 1, 2}
After third rotation arr[] = {2, 3, 4, 1}
After fourth rotation, arr[] returns to its original form.
Input: arr[] = [1]
Output: [1]
方法:
请按照以下步骤解决问题:
- 通过一个一个地执行数组的左旋转来生成数组的所有可能的旋转。
- 打印数组的所有可能旋转,直到遇到相同的数组旋转。
以下是上述方法的实现:
Python
# Python program to print
# all possible rotations
# of the given array
# Function to reverse array
# between indices s and e
def reverse(arr, s, e):
while s < e:
tem = arr[s]
arr[s] = arr[e]
arr[e] = tem
s = s + 1
e = e - 1
# Function to generate all
# possible rotations of array
def fun(arr, k):
n = len(arr)-1
# k = k % n
v = n - k
if v>= 0:
reverse(arr, 0, v)
reverse(arr, v + 1, n)
reverse(arr, 0, n)
return arr
# Driver Code
arr = [1, 2, 3, 4]
for i in range(0, len(arr)):
count = 0
p = fun(arr, i)
print(p, end =" ")
输出:
[1, 2, 3, 4] [4, 1, 2, 3] [2, 3, 4, 1] [3, 4, 1, 2]
时间复杂度: O (N 2 )
辅助空间: O (1)
有关详细信息,请参阅有关打印给定阵列的所有可能旋转的完整文章!