擅长:python、mysql、java
<p>可以使用带递归的生成器:</p>
<pre><code>def combinations(d, _len, current = []):
if len(current) == _len:
yield current
else:
for i in d:
if not current or ('X' in current and current[-1] != i):
yield from combinations(d, _len, current+[i])
results = list(map(''.join, combinations(['X','Y','Z'], 5)))
final_results = [a for i, a in enumerate(results) if a not in results[:i]]
</code></pre>
<p>输出:</p>
<pre><code>['XYXYX', 'XYXYZ', 'XYXZX', 'XYXZY', 'XYZXY', 'XYZXZ', 'XYZYX', 'XYZYZ', 'XZXYX', 'XZXYZ', 'XZXZX', 'XZXZY', 'XZYXY', 'XZYXZ', 'XZYZX', 'XZYZY']
</code></pre>