来制作
原文:
给定一个字符串,您需要打印所有可能的字符串,可以通过在它们之间放置空格(零或一)来实现
示例:
input : str[] = "abc"
output : abc
ab c
a bc
a b c
input : str[] = "abcd"
output : abcd
a bcd
ab cd
a b cd
abc d
a bc d
ab c d
a b c d
如果我们仔细看一下,可以发现这个问题归结为功率设置问题。我们基本上需要生成所有子集,其中每个元素都是不同的空间。
c
// c program to print all strings that can be
// made by placing spaces
#include
using namespace std;
void printsubsequences(string str)
{
int n = str.length();
unsigned int opsize = pow(2, n - 1);
for (int counter = 0; counter < opsize; counter ) {
for (int j = 0; j < n; j ) {
cout << str[j];
if (counter & (1 << j))
cout << " ";
}
cout << endl;
}
}
// driver code
int main()
{
string str = "abc";
printsubsequences(str);
return 0;
}
java 语言(一种计算机语言,尤用于创建网站)
// java program to print all strings that can be
// made by placing spaces
import java.util.*;
class gfg
{
static void printsubsequences(string s)
{
char[] str= s.tochararray();
int n = str.length;
int opsize = (int)(math.pow(2, n - 1));
for (int counter = 0; counter < opsize; counter ) {
for (int j = 0; j < n; j ) {
system.out.print(str[j]);
if ((counter & (1 << j)) > 0)
system.out.print(" ");
}
system.out.println();
}
}
// driver code
public static void main(string[] args)
{
string str = "ab";
printsubsequences(str);
}
}
/* this code is contributed by mr. somesh awasthi */
python 3
# python 3 program to print all strings
# that can be made by placing spaces
from math import pow
def printsubsequences(str):
n = len(str)
opsize = int(pow(2, n - 1))
for counter in range(opsize):
for j in range(n):
print(str[j], end = "")
if (counter & (1 << j)):
print(" ", end = "")
print("\n", end = "")
# driver code
if __name__ == '__main__':
str = "abc"
printsubsequences(str)
# this code is contributed by
# sanjit_prasad
c
// c# program to print all strings
// that can be made by placing spaces
using system;
class gfg {
// function to print all subsequences
static void printsubsequences(string s)
{
char[] str= s.tochararray();
int n = str.length;
int opsize = (int)(math.pow(2, n - 1));
for (int counter = 0; counter < opsize;
counter )
{
for (int j = 0; j < n; j )
{
console.write(str[j]);
if ((counter & (1 << j)) > 0)
console.write(" ");
}
console.writeline();
}
}
// driver code
public static void main()
{
string str = "abc";
printsubsequences(str);
}
}
// this code is contributed by shiv_bhakt.
服务器端编程语言(professional hypertext preprocessor 的缩写)
java 描述语言
输出:
abc
a bc
ab c
a b c
问于: 本文由杰贝辛和忍者供稿。
如果你喜欢 geeksforgeeks 并想投稿,你也可以用写一篇文章或者把你的文章邮寄到 contribute@geeksforgeeks.org。看到你的文章出现在极客博客pg电子试玩链接主页上,帮助其他极客。 如果你发现任何不正确的地方,或者你想分享更多关于上面讨论的话题的信息,请写评论。
麻将胡了pg电子网站的版权属于:月萌api www.moonapi.com,转载请注明出处