zoukankan      html  css  js  c++  java
  • 字符串的所有组合

    问题描述

    给定字符串,求出该字符串的所有组合,即它的所有字串。例如“abc”,应该得到"a","b","c","ab","ac","bc","abc"。

    思路一

    如果没有要求按长度从小到大输出,可以逐位考虑是否选取,代码如下: 

     1 #include<stdio.h>
     2 #include<vector>  
     3 #include<cstring>
     4 using namespace std;
     5 
     6 const int maxn = 100 + 10;
     7 char str[maxn];
     8 vector<char>res;
     9 
    10 //字符串str已排序k个
    11 void Combination(char * str,int k,vector<char>res)
    12 {
    13     if (k == strlen(str))
    14     {
    15         for (int i = 0; i < res.size(); i++)
    16             printf("%c", res[i]);
    17         if(res.size()) printf("
    ");
    18         return;
    19     }
    20     Combination(str, k + 1, res);        //不选第k+1个
    21     res.push_back(str[k]);
    22     Combination(str, k + 1, res);        //选第k+1个  //不选写在前面,不存在要回溯的情况
    23 }
    24 
    25 
    26 int main()
    27 {
    28     scanf("%s", str);
    29     Combination(str, 0, res);
    30     return 0;
    31 }

    思路二

    如果要求按长度从小到大输出,我们可以先考虑长度为len的字串的所有组合,然后让len取1~strlen(str)即可得到所有组合。代码如下:

     1 #include<stdio.h>
     2 #include<iostream>  
     3 #include<vector>  
     4 using namespace std;
     5 
     6 const int maxn = 100 + 10;
     7 char str[maxn];
     8 vector<char>res;
     9 
    10 //字符串str的长度为len的有序排序
    11 void Combination(char* str, int cur,int len, vector<char> res)
    12 {
    13     if (len == 0)
    14     {
    15         for(int i = 0;i < res.size();i++)
    16             printf("%c", res[i]);
    17         printf("
    ");
    18         return;
    19     }
    20     if (cur == strlen(str))  return;    //未得到长为len的字串,要及时退出
    21     res.push_back(str[cur]);
    22     Combination(str, cur + 1, len - 1, res);
    23     res.pop_back();        //回溯
    24     Combination(str,cur + 1,len,res);
    25 }
    26 
    27 void solve(char* str)
    28 {
    29     int len = strlen(str);
    30     for (int i = 1; i <= len; ++i)        //枚举字串的长度
    31         Combination(str,0, i, res);
    32 }
    33 
    34 
    35 int main()
    36 {
    37     scanf("%s", str);
    38     solve(str);
    39 
    40     return 0;
    41 }

    参考链接:https://blog.csdn.net/geekmanong/article/details/50945067

  • 相关阅读:
    开源项目
    [Accessibility] Missing contentDescription attribute on image [可取行]失踪contentDescription属性图像
    Android 布局 中实现适应屏幕大小及组件滚动
    EF 错误记录
    EasyUI 加载时需要显示和隐藏 panel(面板)内容破版问题
    IE 报表缩放后页面破版
    VS 2017 引入nuget 问题
    SSRS 报表显示页面 asp net session丢失或者找不到 asp net session has expired or could not be found()
    log4net 配置
    网站
  • 原文地址:https://www.cnblogs.com/lfri/p/9882432.html
Copyright © 2011-2022 走看看