文章目录

例子:

从数组“abcd",里取3个元素出来

思路:

运用递归的思想,代码比较简单

#include <iostream>
using namespace std;
int n=4 ;
int cnt = 0;//统计组合种类数
char tmp[5]="";//定义一个临时数组来保存抽取到的元素
char s[5] = "abcd";
int k = 3;
void combination(int ind,int len)//从数组s下标为ind的位置开始取元素,
//在tmp数组里已经放了len个元素,下一个元素放在len位置,因为是从0开始的
{
    if(len>=k)//已经取了k个数就可以return了
    {
        cout<<tmp<<endl;
        cnt++;
        return ;
    }
    for(int i=ind;i<n;i++)
    {
        tmp[len] = s[i];//在tmp位置len处放上,s[i]
        combination(i+1,len+1);
    }
}
int main()
{
    combination(0,0);
    cout<<cnt<<endl;
    return 0;
}

废话:

害,本蒟弱听了老师的培训,来写写博客总结
想了解排列问题的博友,可以看我的另一篇博客
三种方法实现全排列