C++实现组合问题(字符数组)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_41038905/article/details/82383772

最近在笔试中看到有一道题目需要用数学上的组合问题罗列出从一个含有n个元素的数组中取出m个元素的所有组合,这个问题当时感觉上可能使用递归的方法可解,但是没有立即写出程序,随后特此记录下来,虽然递归的空间效率比较低,在数组元素数量较多的情况下会程序可能会崩溃,但也算是一种方法,总对递归有种胆怯心里,特此记录一下,首先说明一下C(n,m)表示从n个元素中取出m个的组合。

(1)确定第一个位置可以取得的所有值存入辅助数组temp。

(2)递归C(n-1,m-1),即由于前面已经确定一个数,因此本次递归相当于容量n-1,所取的数m-1。

(3)判断结束,当递归m次即结束。

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include <string>
#include <iostream>

using namespace std;
vector<string> password;
const int M=3;  //选出元素个数
vector<string> c(const char *pwd,char *temp,int n, int m)
{  
    if (m>0)
        {
            for (int i =n;i>=m;i--)
            {
                temp[m-1]=pwd[i-1];         
                c(pwd,temp,i-1,m-1);
            }
        }
        else 
        {   string s;
            for(int i =0 ;i<M;i++)
            {s+=temp[i];}
            password.push_back(s);                  
        }  
  return password; 
}
vector<string> passwordList(const char *pwd,int wordLen,int pwdLen) 
{
    char *temp=new char[pwdLen];        
    vector<string> v;   
    v=c(pwd,temp,wordLen,pwdLen);
    return v;
}
int main()
{  
    char a[5]={'a','b','c','d','e'};    
    vector<string> v= passwordList(a,5,3);  
    for (vector<string>::const_iterator it=v.begin();it!=v.end();++it)  
    {
       cout<<*it<<endl;
    }
    getchar();
    return 0;
}

程序运行结果如图:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/weixin_41038905/article/details/82383772
今日推荐