Lua学习笔记-习题5.4

题目:

函数实现打印出输入矩阵内所有元素的组合。(tips:可以通过递归的方式实现组合,C(n,m)=C(n-1,m-1)+C(n-1,m))。
将该问题进行分解:
1)求数组中由1到n个元素的组合f(n,m) (m>=1 && m<=n;n为数组元素个数);
2)对于f(n,m),从数组中任意取一个元素,然后再从剩下的n-1个元素中取m-1个元素,既f(n-1,m-1);
3)重复第2步,直到f(n-m+1,1),即从n-m+1个元素中取出最后一个元素;
4)把有效的组合压栈,并在压栈前判断该组合在栈中是否存在,避免由于数组元素的重复而导致组合重复。更简单的则是按照矩阵或者数组索引从小到大依次取,避免重复。

代码:

function comb(array)

    local n = #array

    for m = 1, n do

        local used = {}
        local comb = {}

        local function combAux(i, n, m)

            if m == 0 then
                io.write("{ ")
                for i = 1, #comb do
                    io.write(array[comb[i]] .. " ")
                end
                io.write("}")
                print()
            end

            for j = i, n do
                if used[j] ~= true then
                    comb[#comb + 1] = j
                    used[j] = true;
                    combAux(j + 1, n, m - 1)
                    used[j] = false
                    comb[#comb] = nil
                end
            end

        end

        combAux(1, n, m)

    end
end

comb{}
print()
comb{1}
print()
comb{1, 2}
print()
comb{1, 2, 3}
print()
comb{4, 3, 2, 1}

运行结果如下:

你可能感兴趣的:(lua)