算法解读--递归(二)

递归算法思想就是把一个大型复杂的问题层层转化为一个与原问题相似的规模较小的问题来求解。

从模型上来思考的话就需要解决两个要素:递推关系和递推边界。

问题:

数的组合问题,从n个数中选出m个数,结果按照字典序排列。

思路:

每个数的选择都有可能,假设第一个选择的是第i(i从0开始)个数,则剩下的就从i+1到length-1中选择。显然递推的关系很明显。边界也很清楚。

如果熟悉数组操作,应该不难。

参考代码如下:

#include "stdio.h"
#include<iostream>
using namespace std;

#define MAX 100

void combine(int a[], int n, int m, int b[], int M);

int main(void)
{
 int i,n,m;
 int a[MAX], b[MAX];

 cout<<"Hell NOIP!"<<endl;
 cout<<"please enter n:"<<endl;
 cin>>n;
 cout<<"please enter m:"<<endl;
 cin>>m;
 
 if(n<m)
 {
     cout<<"warning n must more than m!";
     return;
 }

 //初始化a数组
 for (i = 1; i < 100; i++)
 {
  a[i - 1] = i;
  }
 combine(a, n, 3, m, 3);
}

void combine(int a[], int n, int m, int b[], int M)
{
 int i, j;

 for (i = n; i >= m; i--)
  {
   b[m - 1] = i - 1;
   if (m > 1)
    combine(a, i - 1, m - 1, b, M);  // 递归关系
   else                               //递归边界
    {
     for (j =0; j <= M-1; j++)
     cout<<a[b[j]]<<" ";
     cout<<endl;
    }
  }
}

在这里插入图片描述
附注:递归算法的理解和运用是学习DFS等搜索算法的基础,通过一些典型的例子加以训练,相信不难掌握。

原创文章 41 获赞 0 访问量 2049

猜你喜欢

转载自blog.csdn.net/qq_21291397/article/details/104511107
今日推荐