回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>生成具有以下约束的所有字符串</p>
<ul>
<li>长度:n</li>
<li>允许字符:a、b、c</li>
<li>最多一个b</li>
<li>最多两个c</li>
</ul>
<p>我编写了以下代码</p>
<pre><code>def generate(s,counta,countb,countc,n,result):
if counta+countb+countc==n:
print(counta,countb,countc)
result.append(s)
print(s)
return
if counta+countb+countc<n and counta<=n:
generate(s+"a",counta+1,countb,countc,n,result)
if counta+countb+countc<n and countb<=1:
generate(s+"b",counta+1,countb+1,countc,n,result)
if counta+countb+countc<n and countc<=2:
generate(s+"c",counta,countb,countc+1,n,result)
result=[]
generate("",0,0,0,3,result)
print(result)
</code></pre>
<p>我得到以下结果,我不明白为什么。一些长度小于n的字符串被添加到结果中</p>
<pre><code>['aaa', 'aac', 'ab', 'aca', 'acc', 'ba', 'bc', 'caa', 'cac', 'cb', 'cca', 'ccc']
</code></pre>
<p><strong>更新代码:(正在工作)</strong></p>
<pre><code>def generate(s,counta,countb,countc,n,result):
if counta+countb+countc==n:
# print(counta,countb,countc)
result.append(s)
# print(s)
return
if counta+countb+countc<n and counta<=n:
generate(s+"a",counta+1,countb,countc,n,result)
if counta+countb+countc<n and countb<1:
generate(s+"b",counta,countb+1,countc,n,result)
if counta+countb+countc<n and countc<2:
generate(s+"c",counta,countb,countc+1,n,result)
result=[]
generate("",0,0,0,3,result)
print(result)
</code></pre>
<p>输出:</p>
<pre><code>['aaa', 'aab', 'aac', 'aba', 'abc', 'aca', 'acb', 'acc', 'baa', 'bac', 'bca', 'bcc', 'caa', 'cab', 'cac', 'cba', 'cbc', 'cca', 'ccb']
</code></pre>