zoukankan      html  css  js  c++  java
  • 用递归实现从M个不同字符中选取N个字符的所有组合

      以前做过类似字符串的题目,当时觉得字符串也能用递归来做非常神奇,后来思考了下,觉得只要抓住字符串是由一个个字符组成的,从第一个字符到最后一个字符每一个都可以作为一次递归,把index作为参数传进去就行,以这种思想为指导才把此题解了出来。 

      对于每个字符只有两种情况,设当前字符串指针为x, 目标字符串指针为y:
      GetString(x,y)= GetString(x+1,y), 不取当前字符
      GetString(x,y) = GetString(x+1,y+1), 取当前字符

      

    1 //////////////////////////////////////////////////////////////////////////
    2  // 递归实现M个字符选N个字符
    3  //
    4 // param:
    5 // origin: original string
    6 // oirIndex: index point to original string
    7 // M: length of original string
    8 // des: destination string
    9 // desIndex: index point to des string
    10 // N: length of des string
    11 //////////////////////////////////////////////////////////////////////////
    12 void GetString(char* origin, int oriIndex, int M, char* des, int desIndex, int N)
    13 {
    14 if(M < N)
    15 return;
    16
    17 //output
    18 if(strlen(des) == N)
    19 {
    20 cout<<des<<endl;
    21 return;
    22 }
    23 //reach the end of origin or des
    24 if(oriIndex == M)
    25 return;
    26 if(desIndex == N)
    27 {
    28 return;
    29 }
    30
    31 //pick oriIndex
    32 des[desIndex]= origin[oriIndex];
    33 GetString(origin,++oriIndex,M,des,++desIndex,N);
    34 //not pick
    35 des[--desIndex] = '\0';
    36 --oriIndex;
    37 GetString(origin,++oriIndex,M,des,desIndex,N);
    38 }
  • 相关阅读:
    对文本抽取词袋模型特征
    jieba分词
    家用电器用户行为分析与事件识别
    Linux系统调用:创建和终止进程
    Linux系统调用:获取进程PID
    使用函数指针解决函数重载二义性调用问题
    C++ string基本操作
    有界深度优先搜索-八数码问题
    数据传送指令
    x86-64数据格式、通用寄存器与操作数格式
  • 原文地址:https://www.cnblogs.com/HappyAngel/p/1867649.html
Copyright © 2011-2022 走看看