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

所以在這個問題中,我們必須按上述方式列印序列。

解決這個問題的一個簡單方法是遞增序列的整數,直到它們達到最大值 n。以下是解決方案的詳細說明。

演算法

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

更新於:2020年1月17日

653 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始學習
廣告