打印给定数组的所有可能旋转的 C++ 程序
给定一个大小为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}
Explanation:
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]
方法:
请按照以下步骤解决问题:
- 通过一个一个地执行数组的左旋转来生成数组的所有可能的旋转。
- 打印数组的所有可能旋转,直到遇到相同的数组旋转。
以下是上述方法的实现:
C++
// C++ program to print
// all possible rotations
// of the given array
#include
using namespace std;
// Global declaration of array
int arr[10000];
// Function to reverse array
// between indices s and e
void reverse(int arr[],
int s, int e)
{
while(s < e)
{
int tem = arr[s];
arr[s] = arr[e];
arr[e] = tem;
s = s + 1;
e = e - 1;
}
}
// Function to generate all
// possible rotations of array
void fun(int arr[], int k)
{
int n = 4 - 1;
int v = n - k;
if (v >= 0)
{
reverse(arr, 0, v);
reverse(arr, v + 1, n);
reverse(arr, 0, n);
}
}
// Driver code
int main()
{
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
for(int i = 0; i < 4; i++)
{
fun(arr, i);
cout << ("[");
for(int j = 0; j < 4; j++)
{
cout << (arr[j]) << ", ";
}
cout << ("]");
}
}
// This code is contributed by Princi Singh
输出:
[1, 2, 3, 4] [4, 1, 2, 3] [2, 3, 4, 1] [3, 4, 1, 2]
时间复杂度: O (N 2 )
辅助空间: O (1)
有关详细信息,请参阅有关打印给定阵列的所有可能旋转的完整文章!