-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuyOrange.php
More file actions
102 lines (72 loc) · 2.14 KB
/
buyOrange.php
File metadata and controls
102 lines (72 loc) · 2.14 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?php
/**
* 第一题
* ⼩⽩去附近店铺买橘⼦,⽬前商店做活动,提供捆绑打包销售,例如每袋 3 个和 每袋 5 个的形式出售。
* 现⼩⽩只想购买 n 个橘⼦,同时想购买尽量少的袋数⽅ 便携带。
* 如果不能购买恰好 n 个橘⼦,就不会购买(可返回-1),求解输出最少 的袋数。(例如:18)
* Class Solution
*/
class Solution
{
//记录袋子个数
private $sum = 0;
//记录所有组合
// private $result = [];
/**
* 思路:题目实际可转化为i*3 + j*5 = $n,要求$i + $j值最小,且不能满足时返回-1
* 采用回溯枚举的方法找出所有可能的组合及记录最小袋子总数
* @param $n
*/
function buy($n)
{
//根据题目,可供选择方案总体转化为【5,3】
$nums = [5, 3];
$this->backTrack($nums, $n, 0, []);
// if(empty($this->result)){
// return -1;
// }
//
// return $this->result;
if (!$this->sum) {
return -1;
}
return $this->sum;
}
/**
* @param $nums 可供选择【5,3】
* @param $total 总个数
* @param $step 阶段
* @param $path 路径
*/
function backTrack($nums, $total, $step, $path)
{
if ($total === 0) {
// $this->result[] = $path;
$sum = count($path);
if ($this->sum == 0) {
$this->sum = $sum;
}
if ($this->sum > $sum) {
$this->sum = $sum;
}
return;
}
if ($step === count($nums)) {
return;
}
for ($i = 0; $i <= intval($total / $nums[$step]); $i++) {
for ($j = 0; $j < $i; $j++) {
//记录可能组合个数
$path[] = $nums[$step];
}
$this->backTrack($nums, $total - $i * $nums[$step], $step + 1, $path);
//撤销选择
for ($j = 0; $j < $i; $j++) {
array_pop($path);
}
}
}
}
//test
$model = new Solution();
var_dump($model->buy(14));