zoukankan      html  css  js  c++  java
  • 利用递归获取字符串有多少种转化可能(从左到右)

    1.c实现

     1 #include<stdio.h>
     2 #include<stdlib.h>
     3 #include<string.h>
     4 //从左往右的尝试
     5 //规定1和A对应,2和B对应、3和C对应...那么一个数字字符串比如”111“
     6 //就可以转化为”AAA” 、“KA”和“AK”
     7 
     8 //给定一个只有数字字符组成的字符串str,返回有多少种转化结果
     9 int process(char *str, int i){
    10     if(i==strlen(str))
    11        return 1;
    12 
    13     //i没有到终止位置
    14     if(str[i]=='0'){
    15         return 0;
    16     }
    17     //str[i]字符不是‘0’
    18     if(str[i]=='1'){
    19         int res = process(str,i+1);//i自己作为单独的部分,后续有多少种方法
    20         if((i+1)<strlen(str))
    21             res += process(str,i+2); //(i和i+1)作为单独的部分,后续有多少种方法
    22         return res;
    23     }
    24     if(str[i]=='2'){
    25        int res = process(str,i+1);//i自己作为单独的部分,后续有多少种方法
    26        //(i和i+1)作为单独的部分并且没有超过26,后续有多少种方法
    27        if((i+1)<strlen(str) && (str[i+1]>='0' && str[i+1]<='6')){
    28            res += process(str,i+2);
    29        }
    30        return res;
    31     }
    32     //str[i] == '3' ~ '9'
    33     return process(str,i+1);
    34 }
    35 
    36 int main(){
    37    char* str = malloc(sizeof(char)*8);
    38    printf("请输入数字字符串:");
    39    scanf("%s",str);
    40    char* ch={'A','B','C','D','E','F','G','H','I','J','K','L','M','N',
    41            'O','P','Q','R','S','T','U','V','W','X','Y','Z'};
    42    int res = process(str,0);
    43    printf("%d",res);
    44    //char c;
    45   // while((c=process(str,0))!= '0'){
    46      // printf(ch);
    47    //}
    48    return 0;
    49 }
  • 相关阅读:
    ASP.NET的三层架构(DAL,BLL,UI)
    页面开发辅助类—HtmlHelper初步了解
    ASP MVC之参数传递
    ASP.NET MVC学习之母版页和自定义控件的使用
    ASP.Net MVC开发基础学习笔记(2):HtmlHelper与扩展方法
    UITableView动态改变Cell高度
    UITableView动态改变Cell高度
    nodejs豆瓣爬虫
    nodejs豆瓣爬虫
    苹果系统OSX中Automator批量重命名
  • 原文地址:https://www.cnblogs.com/indifferent/p/14396797.html
Copyright © 2011-2022 走看看