gpt4 book ai didi

c++ - 生成特定长度的 powerset

转载 作者:太空宇宙 更新时间:2023-11-04 14:15:15 24 4
gpt4 key购买 nike

我使用位移来生成给定数字字符串的幂集。我怎样才能将它限制在一定的长度,比如 4,从而通过不找到不需要的长度的子序列来缩短执行时间。

例如:如果给定的数字字符串是 10292,则只需要以下子序列:1029、102、109、029、0292 等(仅包含数字 4、3、2、1) .

以下是我的代码:

scanf("%s", &str); //read numeric string
int n = strlen(str); //find size of string

// loop to find subsequences or powerset
for ( i = 1; i < ( 1 << n ); ++i ) {
string subseq;
for ( j = 0; j < n; ++j ) {
if ( i & ( 1 << j ) ) {
subseq+=str[j];
}
}

cout << subseq << endl; //print the subsequence
}

最佳答案

只需在打印语句前面放一个过滤器即可。

if (subseq.length() <= 4) cout<<subseq<<endl;

关于c++ - 生成特定长度的 powerset,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11803227/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com