Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

php数组拆分的算法问题

把 字符串 $str = '12,34,5';
拆分成数组 $arr = [[1,3,5],[1,4,5],[2,3,5],[2,4,5]];
求把$str转成$arr的php逻辑算法;


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

说明一下,使用 global 可能看上去不那么优雅,但是这里我就是写一个示例方法,不就过于纠结啦,可自行优化

$str = '12,34,5';
$arr = explode(',', $str);
$step = $book = $result = [];
dfs(0);
print_r($result);


$str = '12,34';
$arr = explode(',', $str);
$step = $book = $result = [];
dfs(0);
print_r($result);

$str = '12,34,5,67';
$arr = explode(',', $str);
$step = $book = $result = [];
dfs(0);
print_r($result);
function dfs($s)
{
    global $arr, $step, $result, $book;
    if (!isset($arr[$s])) {
        $result[] = array_values($step);
        return;
    }

    for ($i = 0; $i < strlen($arr[$s]); $i++) {
        if (!isset($book[$s][$i]) || $book[$s][$i] == 0) {
            $book[$s][$i] = 1;
            $step[$s] = $arr[$s][$i];
            dfs($s + 1);
            $book[$s][$i] = 0;
        }
    }
    return;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...