本文主要是介绍Unity 递归实现数字不重复的排列组合,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
实现
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");
}
效果
这篇关于Unity 递归实现数字不重复的排列组合的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!