在 C++ 中打印给定大小为 n 的数组中 r 个元素的所有可能组合
在这个问题中,我们给定一个大小为 n 的数组和一个正整数 r。我们的任务是打印大小为 r 的数组元素的所有可能组合。
让我们举个例子来理解这个问题:
Input: {5,6,7,8} ; r = 3
Output : {5,6,7}, {5,6,8}, {5,7,8}, {6,7,8}解决这个问题的一种方法是固定元素,然后递归或循环遍历其他元素以找到所有组合。在这里,我们只需要固定前 **n-r+1** 个元素,然后循环或递归遍历其余元素。
示例
#include<iostream>
using namespace std;
void printRElementCombination(int arr[], int combination[], int start, int
end, int index, int r){
if (index == r){
cout<<"{ ";
for (int j = 0; j < r; j++)
cout << combination[j] << " ";
cout<<"}\t";
return;
}
for (int i = start; i <= end && end - i + 1 >= r - index; i++){
combination[index] = arr[i];
printRElementCombination(arr, combination, i+1, end, index+1, r);
}
}
int main(){
int arr[] = {1, 2, 3, 4, 5};
int r = 3;
int n = 5;
int combination[r];
cout<<"The combination is : \n";
printRElementCombination(arr, data, 0, n-1, 0, r);
}输出
组合是:
{ 1 2 3 } { 1 2 4 } { 1 2 5 } { 1 3 4 } { 1 3 5 } { 1 4 5 }
{ 2 3 4 } { 2 3 5 } { 2 4 5 } { 3 4 5 }解决同一问题的其他方法是检查组合中当前元素的包含情况,并打印所有所需大小的组合。其思想相同,我们将递归遍历元素并将组合存储在 combo 数组中。但是,不会固定元素。
下面的程序将使您更容易理解这个问题:
示例
#include <iostream>
using namespace std;
void combinationUtil(int arr[], int n, int r, int index, int combo[], int i){
if (index == r){
cout<<"{";
for (int j = 0; j < r; j++)
cout << combo[j] << " ";
cout<<"}\t";
return;
}
if (i >= n)
return;
combo[index] = arr[i];
combinationUtil(arr, n, r, index + 1, combo, i + 1);
combinationUtil(arr, n, r, index, combo, i+1);
}
int main(){
int arr[] = {1, 2, 3, 4, 5};
int r = 3;
int n = 5;
int combo[r];
cout<<"The combination is : \n";
combinationUtil(arr, n, r, 0, combo, 0);
return 0;
}输出
组合是:
{1 2 3 } {1 2 4 } {1 2 5 } {1 3 4 } {1 3 5 } {1 4 5 }
{2 3 4 } {2 3 5 } {2 4 5 } {3 4 5 }
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP