delphi组合算法

delphi combination algorithm

你好,我不会写组合算法。例如;我有 1 个红球和 2 个白球,我想写数字红球 + 数字白球。像下面一样;

R->Red
W->White

RWW
WRW  
WWR 

我一共有3个组合。但是我怎么能用Delpi写呢?因为,可能是我有 10 RED 8 White 或 15 RED 20 White 等等。我怎么才能订购这个组合。

我有一个规则。

1- 我每次都必须使用所有球。我的订单,组合长度必须是总球。在我的示例中,它必须是 2+1=3.

我该怎么做?

procedure Combination( pLeft : string;pRedCount, pWhiteCount : integer; pResult : strings );
begin
  if (pRedCount = 0) and (pWhiteCount = 0)  then
  begin
    pResult.Add( pLeft );
    exit;
  end;
  if pRedCount > 0 then Combination( pLeft + 'R', pRedCount - 1, pWhiteCount, pResult );
  if pWhiteCount > 0 then Combination( pLeft + 'W', pRedCount, pWhiteCount - 1, pResult )

end;

例如,如果在您的主程序中有一个名为 Memo 的 TMemo,一个名为 RCount 的 spineedit 和另一个名为 WCount,那么您将在您的操作按钮上执行

Memo.Lines.Clear
Combination( '', RCount.Value, WCount.Value, Memo.Lines );