16 June 2017

今天,同事有个需求,是一个算法的实现,大概想要实现的就是:
有几组数据,如下:

a1, a2, a3
b1, b2
c1, c2, c3

大概要处理成

a1, b1, c1
a1, b1, c2
a1, b1, c3

a1, b2, c1
a1, b2, c2
a1, b2, c3

a2, b1, c1
a2, b1, c2
a2, b1, c3

a2, b2, c1
a2, b2, c2
a2, b2, c3

a3, b1, c1
a3, b1, c2
a3, b1, c3

a3, b2, c1
a3, b2, c2
a3, b2, c3

由于这样的数据不一定只有 3 组,直接想到的做法就是递归回溯

$tmpArr = [
    [
        "a1", "a2", "a3"
    ],
    [
        "b1", "b2"
    ],
    [
        "c1", "c2", "c3"
    ]
];

$res = [];

function dfs($arr, $index, $cur) {
    global $res;
    if ($index+1 == count($arr)) {
        $tmp = $cur;
        foreach ($arr[$index] as $v) {
            array_push($cur, $v);
            array_push($res, $cur);
            $cur = $tmp;
        }
    } else {
        foreach ($arr[$index] as $v) {
            array_push($cur, $v);
            dfs($arr, $index+1, $cur);
            array_pop($cur);
        }
    }
}

dfs($tmpArr, 0, []);
var_dump($res);

在工作中,真的没怎么用过算法,今天算是秀了一波