# 如何将值从递归函数返回到数组

``````function nestedLoop(depth::Integer, n::Integer, symbArr, len::Integer, k::Integer, num_arr)
for i = k:len
num_arr[depth-n+1] = symbArr[i]
n == 1 && println(num_arr)
(n > 1) && nestedLoop(depth, n-1, symbArr, len, i, num_arr)
end
end

function combwithrep(symbArr, n::Integer)
len = length(symbArr)
num_arr = Array(eltype(symbArr),n)
nestedLoop(n, n, symbArr, len, 1, num_arr)
end
@time combwithrep(["+","-","*","/"], 3)
``````

rickhg12hs

``````julia> function nested_loop{T <: Integer, V <: AbstractVector}(depth::T, n::T, symb_arr::V, len::T, k::T, num_arr::V, result::Array{V,1})
for i = k:len
num_arr[depth-n+1] = symb_arr[i]
n == 1 ? push!(result, deepcopy(num_arr)) : nested_loop(depth, n-1, symb_arr, len, i, num_arr, result)
end
end
nested_loop (generic function with 1 method)

julia> function combwithrep(symb_arr::AbstractVector, n::Integer)
len = length(symb_arr)
num_arr = Array(eltype(symb_arr),n)
result = Array{typeof(num_arr)}(0)
nested_loop(n, n, symb_arr, len, 1, num_arr, result)
return result
end
combwithrep (generic function with 1 method)

julia> combwithrep(['+', '-', '*', '/'], 3)
20-element Array{Array{Char,1},1}:
['+','+','+']
['+','+','-']
['+','+','*']
['+','+','/']
['+','-','-']
['+','-','*']
['+','-','/']
['+','*','*']
['+','*','/']
['+','/','/']
['-','-','-']
['-','-','*']
['-','-','/']
['-','*','*']
['-','*','/']
['-','/','/']
['*','*','*']
['*','*','/']
['*','/','/']
['/','/','/']
``````

0条评论