排列组合Lua实现 - 图1

    1. --全排列
    2. function fullPermutation(fullArray, startPos,endPos)
    3. local function swap(i1, i2,arr)
    4. local temp = arr[i2];
    5. arr[i2] = arr[i1];
    6. arr[i1] = temp;
    7. end
    8. startPos = startPos or 1
    9. endPos = endPos or #fullArray
    10. if startPos >= endPos then
    11. print(table.concat(fullArray,","))
    12. return
    13. else
    14. for j = startPos,endPos do
    15. --for循环将每个数放到start位置中去
    16. swap(startPos,j,fullArray);
    17. --剩下的数继续递归,下一个位置,一维问题
    18. fullPermutation(fullArray,startPos + 1,endPos);
    19. --回溯
    20. swap(startPos,j,fullArray);
    21. end
    22. end
    23. end
    24. --组合
    25. function combination(arr,nCount,resultArr,head)
    26. head = head or 1
    27. resultArr = resultArr or {}
    28. if (#resultArr == nCount ) then
    29. --组合选的结果出来
    30. print(table.concat(resultArr,","))
    31. else
    32. for i = head,#arr do
    33. if(#resultArr < nCount ) then
    34. table.insert(resultArr,arr[i])
    35. combination(arr,nCount,resultArr,i + 1)
    36. --回溯还原
    37. table.remove(resultArr)
    38. end
    39. end
    40. end
    41. end
    42. --所有组合
    43. function allCombination(arr)
    44. for i = 1,#arr do
    45. combination(arr,i)
    46. end
    47. end
    48. --所有排列
    49. function allPermutation(arr)
    50. function combination(arr,nCount,resultArr,head)
    51. head = head or 1
    52. resultArr = resultArr or {}
    53. if (#resultArr == nCount ) then
    54. --组合选的结果出来
    55. --print(table.concat(resultArr,","))
    56. --组合结果
    57. fullPermutation(resultArr)
    58. else
    59. for i = head,#arr do
    60. if(#resultArr < nCount ) then
    61. table.insert(resultArr,arr[i])
    62. combination(arr,nCount,resultArr,i + 1)
    63. --回溯还原
    64. table.remove(resultArr)
    65. end
    66. end
    67. end
    68. end
    69. for i = 1,#arr do
    70. combination(arr,i)
    71. end
    72. end
    73. --注意排列中的数字不能重复
    74. --测试代码,在luaEditor中测试通过
    75. local Data = {4,5,6}
    76. --fullPermutation(Data)
    77. allPermutation(Data)
    78. --allCombination(Data)
    79. --combination(Data,2)