-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombinationSum.php
More file actions
54 lines (36 loc) · 1.12 KB
/
combinationSum.php
File metadata and controls
54 lines (36 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?php
class Solution
{
public $result = [];
/**
* 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
* candidates 中的数字可以无限制重复被选取。
* @param Integer[] $candidates
* @param Integer $target
* @return Integer[][]
*/
function combinationSum($candidates, $target)
{
$this->backTrack($candidates, $target, 0, []);
return $this->result;
}
function backTrack($candidates, $left, $step, $path)
{
if($left === 0){
$this->result[] = $path;
return;
}
if($step === count($candidates)){
return;
}
for ($i = 0; $i <= intval($left / $candidates[$step]); $i++){
for ($j = 0; $j < $i; $j++){
$path[] = $candidates[$step];
}
$this->backTrack($candidates, $left - $i * $candidates[$step], $step + 1, $path);
for ($j = 0; $j < $i; $j++){
array_pop($path);
}
}
}
}