遞迴列印C++中由單詞列表組成的所有句子


給定一個單詞列表。目標是使用遞迴方法建立所有可能的句子,這些句子可以透過從列表中取詞來形成。你每次只能從列表中取一個詞。

讓我們看看這個的各種輸入輸出場景

輸入 

sentence[row][col] = {{"I", "You"},
   {"Do", "do not like"},
   {"walking", "eating"}}

輸出   

I Do walking
I Do eating
I like walking
I like eating
You Do walking
You Do eating
You like walking
You like eating

說明 − 從sentence[0-2]中的每個列表中取一個詞得到上面的句子。

輸入 

sentence[row][col] = {{"work", "live"},{"easy", "happily"}}

輸出 

work easy
work happily
live easy
live happily

說明 − 從sentence[0-1]中的每個列表中取一個詞得到上面的句子。

  • 宣告一個二維字串陣列sentence[row][col]。將資料作為Recursive_Print(sentence)傳遞給函式。

  • 在函式Recursive_Print(sentence)內部

    • 建立一個字串型別的陣列arr[row]。

    • 從i=0開始迴圈,直到i小於col。在迴圈內,檢查IF sentence[0][i]不為空,則呼叫函式Recursion(sentence, 0, i, arr)。

  • 在函式Recursion(string sentence[row][col], int temp_1, int temp_2, string arr[row])內部

    • 將arr[temp_1]設定為sentence[temp_1][temp_2]。

    • 檢查IF temp_1等於row - 1,則從i=0開始迴圈,直到i小於row。在迴圈內,列印arr[i]。

    • 從i=0開始迴圈,直到i小於col。在迴圈內,檢查IF sentence[temp_1+1][i]不等於空格,則遞迴呼叫函式Recursion(sentence, temp_1+1, i, arr)。

  • 列印結果。

下面程式中使用的方法如下

示例

#include<bits/stdc++.h>
#define row 3
#define col 3
using namespace std;
void Recursion(string sentence[row][col], int temp_1, int temp_2, string arr[row]){
   arr[temp_1] = sentence[temp_1][temp_2];
   if(temp_1 == row - 1){
      for(int i=0; i < row; i++){
         cout << arr[i] << " ";
      }
      cout << endl;
      return;
   }
   for(int i=0; i < col; i++){
      if(sentence[temp_1+1][i] != ""){
         Recursion(sentence, temp_1+1, i, arr);
      }
   }
}
void Recursive_Print(string sentence[row][col]){
   string arr[row];
   for(int i=0; i < col; i++){
      if(sentence[0][i] != ""){
         Recursion(sentence, 0, i, arr);
      }
   }
}
int main(){
   string sentence[row][col] = {{"Ajay", "sanjay"},{"Like", "is"},{"Reading", "eating"}};
   Recursive_Print(sentence);
   return 0;
}

輸出

如果我們執行上面的程式碼,它將生成以下輸出

Ajay Like Reading
Ajay Like eating
Ajay is Reading
Ajay is eating
sanjay Like Reading
sanjay Like eating
sanjay is Reading
sanjay is eating

更新於: 2021年11月3日

432 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告