实现
private void Permutation(List<int> num, int leftIndex, List<string> strs)
{
if (leftIndex < num.Count)
{
for (int rightIndex = leftIndex; rightIndex < num.Count; rightIndex++)
{
Swap(num, leftIndex, rightIndex);
Permutation(num, leftIndex + 1, strs);
Swap(num, rightIndex, leftIndex);
}
}
else
{
string s = string.Empty;
for (int i = 0; i < num.Count; i++)
{
s += num[i].ToString();
if (i < num.Count - 1)
s += "→";
}
strs.Add(s);
}
}
void Swap(List<int> num, int leftIndex, int rightIndex)
{
int temp = num[leftIndex];
num[leftIndex] = num[rightIndex];
num[rightIndex] = temp;
}
示例
List<int> num = new List<int>() { 1, 2 };
Permutation(num);
num = new List<int>() { 1, 2, 3 };
Permutation(num);
private void Permutation(List<int> num)
{
List<string> strs = new List<string>();
Permutation(num, 0, strs);
string strNum = string.Empty;
for (int i = 0; i < num.Count; i++)
{
strNum += num[i].ToString();
if (i < num.Count - 1)
strNum += ",";
}
Debug.Log(strNum + " 排列组合共 " + strs.Count + " 组");
for (int i = 0; i < strs.Count; i++)
Debug.Log(strs[i] + "\n");
}
效果