-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombinations.php
More file actions
53 lines (35 loc) · 935 Bytes
/
combinations.php
File metadata and controls
53 lines (35 loc) · 935 Bytes
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
<?php
class Solution {
public $result = [];
/**
* 给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
* @param Integer $n
* @param Integer $k
* @return Integer[][]
*/
function combine($n, $k) {
if(!$n || !$k){
return [];
}
$this->backTrack($n, $k, 1, []);
return $this->result;
}
function backTrack($n, $k, $step, $path)
{
if(count($path) === $k){
$this->result[] = $path;
return;
}
if($step === $n + 1)
return;
//$step不放入解集$path情况
$this->backTrack ($n, $k, $step + 1, $path);
//$step放入解集$path情况
$path[] = $step;
$this->backTrack($n, $k, $step + 1, $path);
//还原
array_pop($path);
}
}
$model = new Solution();
var_dump($model->combine(4, 2));