字符串的所有组合

问题描述

给定字符串,求出该字符串的所有组合,即它的所有字串。例如“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("\n");
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("\n");
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

猜你喜欢

转载自www.cnblogs.com/lfri/p/9882432.html