在C ++中打印给定长度的所有序列

在这个问题中,我们给了两个整数值k和n。而且我们必须按顺序打印从1到n的所有长度为k的序列。

让我们以一个例子来理解这个话题-

Input:k = 2 ; n = 3
Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

因此在此问题中,我们必须如上 打印顺序。

解决此问题的一种简单方法是递增序列的整数,直到它们达到最大值ien。以下是解决方案的详细说明。

算法

1) Create an array of size k with all values = 1 i.e. {1, 1, ..ktimes}.
2) Repeat step 3 and 4 till the array becomes {n, n, …, n}.
3) Print the array.
4) Increment the value such that the elements of the array become the next value. For example, {1, 1, 1} incremented to {1, 1, 2} and {1, 3, 3} incremented to {2, 1, 1}. For this we need to check the kth element of the array, if it’s equal to n become update, then check k-1 element in the sequence and so on for the same condition.

示例

以下程序将使您更清楚地了解该概念。

#include<iostream>
using namespace std;
void printSequence(int arr[], int size){
   for(int i = 0; i < size; i++)
      cout<<arr[i]<<"\t";
   cout<<endl;
   return;
}
int nextElement(int arr[], int k, int n){
   int s = k - 1;
   while (arr[s] == n)
      s--;
   if (s < 0)
      return 0;
   arr[s] = arr[s] + 1;
   for(int i = s + 1; i < k; i++)
      arr[i] = 1;
   return 1;
}
void generateSequence(int n, int k){
   int *arr = new int[k];
   for(int i = 0; i < k; i++)
      arr[i] = 1;
   while(1){
      printSequence(arr, k);
   if(nextElement(arr, k, n) == 0)
      break;
   }
   return;
}
int main(){
   int n = 3;
   int k = 2;
   cout<<"The sequence is :\n";
   generateSequence(n, k);
   return 0;
}

输出结果

顺序是-

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

这种方法易于理解,但可以做得更好,更有效。

此方法使用递归和额外的索引来检查序列偏移量(该值之后将翻转序列)。该函数将递归调用,并且直到索引才更新术语。并在索引后重新设置下一项功能。

示例

#include<iostream>
using namespace std;
void printSequence (int arr[], int size){
   for (int i = 0; i < size; i++)
      cout << arr[i] << "\t";
   cout << endl;
   return;
}
void generateSequence (int arr[], int n, int k, int index){
   int i;
   if (k == 0){
      printSequence (arr, index);
   }
   if (k > 0){
      for (i = 1; i <= n; ++i){
         arr[index] = i;
         generateSequence (arr, n, k - 1, index + 1);
      }
   }
}
int main (){
   int n = 3;
   int k = 2;
   int *arr = new int[k];
   cout<<"The sequence is:\n";
   generateSequence (arr, n, k, 0);
   return 0;
}

输出结果

顺序是-

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3