@Ed'ka 提供的解决方案简洁而漂亮,但尽管如此,它的复杂性是O(N)
.
我建议您考虑通过平方方法求幂,它提供O(log(N))
了幂计算的复杂性。使用这种技术,笛卡尔幂可以这样实现:
%% Entry point
cart(List, N) ->
Tmp = [[X] || X <- List],
cart(Tmp, Tmp, N).
cart(_InitialList, CurrList, 1) ->
CurrList;
cart(_InitialList, CurrList, N) when N rem 2 == 0 ->
Tmp = mul(CurrList, CurrList),
cart(Tmp, Tmp, N div 2);
cart(InitialList, CurrList, N) ->
Tmp = cart(InitialList, CurrList, N - 1),
mul(InitialList, Tmp).
mul(L1, L2) ->
[X++Y || X <- L1, Y <- L2].
PS shell 的使用示例(我已将函数打包cart
到 mudule 中my_module
):
1> c(my_module).
{ok,my_module}
2>
2> my_module:cart([0,1], 2).
[[0,0],[0,1],[1,0],[1,1]]
3>
3> my_module:cart([0,1], 3).
[[0,0,0],
[0,0,1],
[0,1,0],
[0,1,1],
[1,0,0],
[1,0,1],
[1,1,0],
[1,1,1]]