回溯算法 发表于 2020-02-27 | 分类于 算法 , 回溯算法 | 本文总阅读量 题目一全排列 123456789101112131415161718192021222324252627282930class Solution { private $list_path = []; /** * @param Integer[] $nums * @return Integer[][] */ function permute($nums) { if(count($nums) == 0) { return []; } $this->backtrace($nums, 0); return $this->list_path; } function backtrace($nums, $start) { if ($start == count($nums)) { $this->list_path[] = $nums; } for($i=$start;$i<count($nums);$i++) { $this->swap($nums[$start], $nums[$i]); $this->backtrace($nums, $start+1); $this->swap($nums[$start], $nums[$i]); } } function swap(&$i, &$j) { $t = $i; $i = $j; $j = $t; }} ##题目二组合总数 1234567891011121314151617181920212223242526272829class Solution { public $path = []; public $sums = []; /** * @param Integer[] $candidates * @param Integer $target * @return Integer[][] */ function combinationSum($candidates, $target) { $length = count($candidates); if ($length == 0) { return []; } sort($candidates); $this->dfs($candidates, 0, $target); return $this->sums; } function dfs($candidates, $start, $target) { if ($target == 0) { $this->sums[] = $this->path; } for($i = $start;$i<count($candidates) && ($target-$candidates[$i]>=0);$i++) { $this->path[] = $candidates[$i]; $this->dfs($candidates, $i, $target-$candidates[$i]); array_pop($this->path); } }} 题目三电话号码字母组合 123456789101112131415161718192021222324252627282930313233343536373839class Solution { const ALPHA = [ 2 => 'abc', 3 => 'def', 4 => 'ghi', 5 => 'jkl', 6 => 'mno', 7 => 'pqrs', 8 => 'tuv', 9 => 'wxyz', ]; private $output = []; /** * @param String $digits * @return String[] */ function letterCombinations($digits) { if (strlen($digits) == 0) { return []; } $len = strlen($digits); $this->combine("", $digits); return $this->output; } function combine($combine, $digits) { if (strlen($digits) == 0) { array_push($this->output, $combine); return; } for($i=0;$i<strlen(self::ALPHA[$digits[0]]);$i++) { $letter = self::ALPHA[$digits[0]][$i]; $this->combine($combine.$letter, substr($digits, 1)); } } }