All sequences Foundations of Fortune left print string class8- Title 3

All sequences Foundations of Fortune left print string class8- Title 3

1. Title: printing a string of all the sub-sequence, including the empty string

2. Analysis

If the string abc, all sub-strings may be: empty, a, ab, ac, abc, b, bc, c

For each element of the string, we can choose to or not, as shown below, the current element if needed, get an "a" first element do not need it then the first one is "", and then went back judge, b elements still need to be selected or not, then there are four possible "ab", "a", "b", "". It is the same reason for the next element c. The end of the current condition of the entire recursive index are not in the string
Here Insert Picture Description

3. The complete code

#include<iostream>
#include<string>
using namespace std;

//s是给定的字符串,i是索引,res是结果
void print(const string s,int i,string res)
{
	if(i == s.size())	//超出索引,打印上一级传递的结果
	{
		cout<<res<<endl;
		return;
	}
	else
	{
		print(s,i + 1,res + s[i]);	//添加当前字符
		print(s,i + 1,res );		//丢弃当前字符
	}
}

int main()
{
	string s = "abc";
	string res;
	print(s,0,res );

	return 0;
}
Published 51 original articles · won praise 1 · views 1363

Guess you like

Origin blog.csdn.net/shi_xiao_xuan/article/details/104823699