[CareerCup][Google Interview] 打印组合

本文介绍了一个用于计算字符串中不重复子串数量的算法,通过使用标记数组来避免重复计数,适用于字符串处理场景。

http://www.careercup.com/question?id=3315662

given a string find the number of distinct substrings of the string.
ex:
input-> aaaa
output-> 4(a, aa, aaa, aaaa)
input->abcd
output->10(a, b, c, d, ab, bc, cd, abc, bcd, abcd)

 

我的方法避免重复是设置一个used数组,记录每个数被使用的情况,如果当前的数和它前一个数相同,则前一个数必须被使用了,当前数才能被使用,这样就能避免了重复出现。

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 
 5 bool used[100];
 6 
 7 void solve(int dep, int maxDep, string &s, string ans, int start)
 8 {
 9     if (dep != 0)
10         cout << ans << endl;
11 
12     if (dep == maxDep)
13         return;
14 
15     for(int i = start; i < s.size(); i++)
16     {
17         if (i == 0)
18         {
19             used[i] = true;
20             solve(dep + 1, maxDep, s, ans + s[i], i + 1);
21             used[i] = false;
22         }
23         else
24         {
25             if (s[i] == s[i-1])
26             {
27                 if (used[i-1])
28                 {
29                     used[i] = true;
30                     solve(dep + 1, maxDep, s, ans + s[i], i + 1);
31                     used[i] = false;
32                 }
33             }
34             else
35             {
36                 used[i] = true;
37                 solve(dep + 1, maxDep, s, ans + s[i], i + 1);
38                 used[i] = false;
39             }
40         }
41     }
42 }
43 
44 int main()
45 {
46     string a = "aaaa";
47     memset(used, false, sizeof(used));
48     solve(0, a.size(), a, "", 0);
49 
50     string b = "abcd";
51     memset(used, false, sizeof(used));
52     solve(0, a.size(), b, "", 0);
53 }

 

 

转载于:https://www.cnblogs.com/chkkch/archive/2012/11/06/2756568.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值