From 884e5f9c8c94726e5cce7ac7337bc0aaadb44b08 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Mon, 16 Nov 2020 22:58:05 +0800 Subject: [PATCH 001/192] =?UTF-8?q?=E5=85=88=E6=8F=90=E4=BA=A4=E7=AC=AC?= =?UTF-8?q?=E4=B8=80=E5=91=A8=E9=83=A8=E5=88=86=E4=BD=9C=E4=B8=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + Week1/189.rotate-array.php | 105 ++++++++++++++++++ ...26.remove-duplicates-from-sorted-array.php | 27 +++++ 3 files changed, 133 insertions(+) create mode 100644 .gitignore create mode 100644 Week1/189.rotate-array.php create mode 100644 Week1/26.remove-duplicates-from-sorted-array.php diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..9f11b755 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.idea/ diff --git a/Week1/189.rotate-array.php b/Week1/189.rotate-array.php new file mode 100644 index 00000000..472384de --- /dev/null +++ b/Week1/189.rotate-array.php @@ -0,0 +1,105 @@ +reverse($nums, 0, $len - 1); + $this->reverse($nums, 0, $k - 1); + $this->reverse($nums, $k, $len - 1); + } + + /** + * 反转数组 + * @param $arr + * @param $l + * @param $r + */ + function reverse(&$arr, $l, $r) + { + while ($l < $r) { + $tmp = $arr[$l]; + $arr[$l] = $arr[$r]; + $arr[$r] = $tmp; + $l++; + $r--; + } + } +} + +$in = [-1]; +$in = [1, 2, 3, 4, 5, 6, 7]; +$k = 3; +$s = new Solution(); +$ret = $s->rotate($in, $k); +print_r($in); \ No newline at end of file diff --git a/Week1/26.remove-duplicates-from-sorted-array.php b/Week1/26.remove-duplicates-from-sorted-array.php new file mode 100644 index 00000000..d5c63425 --- /dev/null +++ b/Week1/26.remove-duplicates-from-sorted-array.php @@ -0,0 +1,27 @@ +removeDuplicates($in); +print_r($out); +print_r($in); \ No newline at end of file From 20964f903ace737b497fab50731c34e9b9e4367d Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Tue, 17 Nov 2020 12:00:34 +0800 Subject: [PATCH 002/192] =?UTF-8?q?20.=E6=9C=89=E6=95=88=E6=8B=AC=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week1/20.valid-parentheses.php | 49 ++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Week1/20.valid-parentheses.php diff --git a/Week1/20.valid-parentheses.php b/Week1/20.valid-parentheses.php new file mode 100644 index 00000000..f23cdc68 --- /dev/null +++ b/Week1/20.valid-parentheses.php @@ -0,0 +1,49 @@ +push(')'); + } elseif ($s[$i] == '[') { + $stack->push(']'); + } elseif ($s[$i] == '{') { + $stack->push('}'); + } elseif ($stack->isEmpty() || $stack->pop() != $s[$i]) { + return false; + } + } + return $stack->isEmpty(); + } + + /** + * 二、替换 时间复杂度较高 + * @param String $s + * @return Boolean + */ + function isValid2($s) { + $count = strlen($s); + for ($i = 0; $i < $count / 2; $i++) { + $s = str_ireplace("{}", '', $s); + $s = str_ireplace("[]", '', $s); + $s = str_ireplace("()", '', $s); + } + return strlen($s) > 0 ? false : true; + } +} + +$in = "("; +$in = "]]"; +$in = "]"; +$in = "()[]{}"; +$in = "(("; +$s = new Solution(); +$ret = $s->isValid($in); +var_dump($ret); \ No newline at end of file From 9b36adfd9305ef84f2930b3edb5bbbe185548bb9 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Tue, 17 Nov 2020 14:21:20 +0800 Subject: [PATCH 003/192] =?UTF-8?q?=E6=9C=80=E5=B0=8F=E6=A0=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week1/155.min-stack.php | 87 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 Week1/155.min-stack.php diff --git a/Week1/155.min-stack.php b/Week1/155.min-stack.php new file mode 100644 index 00000000..620f0ca0 --- /dev/null +++ b/Week1/155.min-stack.php @@ -0,0 +1,87 @@ +stack = []; + $this->mStack = []; + $this->index = -1; + } + + /** + * @param Integer $x + * @return NULL + */ + function push($x) + { + $this->index++; + $this->stack[$this->index] = $x; + $this->mStack[$this->index] = empty($this->mStack) ? $x : ($x < $this->mStack[$this->index - 1] ? $x : $this->mStack[$this->index - 1]); + } + + /** + * @return NULL + */ + function pop() + { + unset($this->stack[$this->index]); + unset($this->mStack[$this->index]); + $this->index--; + } + + /** + * @return Integer + */ + function top() + { + return $this->stack[$this->index]; + } + + /** + * @return Integer + */ + function getMin() + { + return $this->mStack[$this->index]; + } +} + +/** + * Your MinStack object will be instantiated and called as such: + * $obj = MinStack(); + * $obj->push($x); + * $obj->pop(); + * $ret_3 = $obj->top(); + * $ret_4 = $obj->getMin(); + */ + +$minStack = new MinStack(); +//$minStack->push(-2); +//$minStack->push(0); +//$minStack->push(-3); +//echo $minStack->getMin() . PHP_EOL; //--> 返回 -3. +//$minStack->pop(); +//echo $minStack->top() . PHP_EOL; //--> 返回 0. +//echo $minStack->getMin() . PHP_EOL; //--> 返回 -2. + +$minStack->push(2147483646); +$minStack->push(2147483646); +$minStack->push(2147483647); +echo '1:'. $minStack->top() . PHP_EOL; //--> 返回 . +$minStack->pop(); +echo '2:'. $minStack->getMin() . PHP_EOL; //--> 返回 . +$minStack->pop(); +echo '3:'. $minStack->getMin() . PHP_EOL; //--> 返回 . +$minStack->pop(); +$minStack->push(2147483647); +echo '4:'. $minStack->top() . PHP_EOL; //--> 返回 . +echo '5:'. $minStack->getMin() . PHP_EOL; //--> 返回 . +$minStack->push(-2147483648); +echo '6:'. $minStack->top() . PHP_EOL; //--> 返回 . +echo '7:'. $minStack->getMin() . PHP_EOL; //--> 返回 . +$minStack->pop(); +echo '8:'. $minStack->getMin() . PHP_EOL; //--> 返回 . From 1cbadfcb07085947a017b7cf7d4e10d695c3bbce Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 18 Nov 2020 09:47:31 +0800 Subject: [PATCH 004/192] =?UTF-8?q?=E6=9F=B1=E7=8A=B6=E5=9B=BE=E4=B8=AD?= =?UTF-8?q?=E7=9A=84=E6=9C=80=E5=A4=A7=E7=9F=A9=E5=BD=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week1/84.largest-rectangle-in-histogram.php | 65 +++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 Week1/84.largest-rectangle-in-histogram.php diff --git a/Week1/84.largest-rectangle-in-histogram.php b/Week1/84.largest-rectangle-in-histogram.php new file mode 100644 index 00000000..dcb961c8 --- /dev/null +++ b/Week1/84.largest-rectangle-in-histogram.php @@ -0,0 +1,65 @@ +push(-1); + $count = count($heights); + $maxArea = 0; + for ($i = 0; $i < $count; $i++) { + $height = $heights[$i]; + while (!$stack->isEmpty() && $heights[$stack->top()] > $height) { + $j = $stack->pop(); + $maxArea = max($maxArea, $heights[$j] * ($i - $stack->top() - 1)); + } + $stack->push($i); + } + $r = $stack->top(); + while (!$stack->isEmpty() && $stack->top() != -1) { + $j = $stack->pop(); + $l = $stack->top(); + $maxArea = max($maxArea, $heights[$j] * ($r - $l)); + } + return $maxArea; + } + + /** + * 一、暴力枚举柱体高度 O(n^2) O(1) + * @param Integer[] $heights + * @return Integer + */ + function largestRectangleArea2($heights) + { + $count = count($heights); + $maxArea = 0; + for ($i = 0; $i < $count; $i++) { + $height = $heights[$i]; + $lp = $i - 1; + $rp = $i + 1; + while ($lp >= 0 && $heights[$lp] >= $heights[$i]) { + $lp--; + } + while ($rp < $count && $heights[$rp] >= $heights[$i]) { + $rp++; + } + $maxArea = max($maxArea, $height * ($rp - $lp - 1)); + } + return $maxArea; + } +} + +$in = [2, 1, 5, 6, 2, 3]; +$in = [2,1,5,6,2,3]; +$in = [2,1,2]; +$in = [0]; +$s = new Solution(); +$ret = $s->largestRectangleArea($in); +print_r($ret); \ No newline at end of file From aebce97b5e9c49088f5231cd48873b9247afa32b Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 18 Nov 2020 17:16:22 +0800 Subject: [PATCH 005/192] =?UTF-8?q?=E6=BB=91=E5=8A=A8=E7=AA=97=E5=8F=A3?= =?UTF-8?q?=E6=9C=80=E5=A4=A7=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week1/239.sliding-window-maximum.php | 44 ++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Week1/239.sliding-window-maximum.php diff --git a/Week1/239.sliding-window-maximum.php b/Week1/239.sliding-window-maximum.php new file mode 100644 index 00000000..14b6b4fc --- /dev/null +++ b/Week1/239.sliding-window-maximum.php @@ -0,0 +1,44 @@ +isEmpty() && $deque->top() < $nums[$i]) { + $deque->pop(); + } + $deque->enqueue($nums[$i]); + } + $ret[] = $deque->bottom(); + for ($i = $k; $i < $count; $i++) { + if ($nums[$i - $k] == $deque->bottom()) { + $deque->dequeue(); + } + while (!$deque->isEmpty() && $deque->top() < $nums[$i]) { + $deque->pop(); + } + $deque->enqueue($nums[$i]); + $ret[] = $deque->bottom(); + } + return $ret; + } +} + +$in = [1, 3, -1, -3, 5, 3, 6, 7]; +$in = [1, -1]; +$k = 3; +$k = 1; +$s = new Solution(); +$ret = $s->maxSlidingWindow($in, $k); +print_r($ret); \ No newline at end of file From 7a2d705d9a83377da8c12d29064c3ef6ed18f1c9 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 18 Nov 2020 18:08:06 +0800 Subject: [PATCH 006/192] =?UTF-8?q?=E8=AE=BE=E8=AE=A1=E5=8F=8C=E7=AB=AF?= =?UTF-8?q?=E9=98=9F=E5=88=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week1/641.design-circular-deque.php | 130 ++++++++++++++++++++++++++++ 1 file changed, 130 insertions(+) create mode 100644 Week1/641.design-circular-deque.php diff --git a/Week1/641.design-circular-deque.php b/Week1/641.design-circular-deque.php new file mode 100644 index 00000000..8d529ecc --- /dev/null +++ b/Week1/641.design-circular-deque.php @@ -0,0 +1,130 @@ +deque = []; + $this->count = 0; + $this->capacity = $k; + } + + /** + * Adds an item at the front of Deque. Return true if the operation is successful. + * @param Integer $value + * @return Boolean + */ + function insertFront($value) + { + if (!$this->isFull()) { + array_unshift($this->deque, $value); + $this->count++; + return true; + } else { + return false; + } + } + + /** + * Adds an item at the rear of Deque. Return true if the operation is successful. + * @param Integer $value + * @return Boolean + */ + function insertLast($value) + { + if(!$this->isFull()) { + array_push($this->deque,$value); + $this->count++; + return true; + }else{ + return false; + } + } + + /** + * Deletes an item from the front of Deque. Return true if the operation is successful. + * @return Boolean + */ + function deleteFront() + { + if (!$this->isEmpty()) { + array_shift($this->deque); + $this->count--; + return true; + } else { + return false; + } + } + + /** + * Deletes an item from the rear of Deque. Return true if the operation is successful. + * @return Boolean + */ + function deleteLast() + { + if (!$this->isEmpty()) { + array_pop($this->deque); + $this->count--; + return true; + } else { + return false; + } + } + + /** + * Get the front item from the deque. + * @return Integer + */ + function getFront() + { + return $this->deque[0] ?? -1; + } + + /** + * Get the last item from the deque. + * @return Integer + */ + function getRear() + { + return $this->deque[$this->count - 1] ?? -1; + } + + /** + * Checks whether the circular deque is empty or not. + * @return Boolean + */ + function isEmpty() + { + return $this->count > 0 ? false : true; + } + + /** + * Checks whether the circular deque is full or not. + * @return Boolean + */ + function isFull() + { + return ($this->count == $this->capacity) ? true : false; + } +} + +/** + * Your MyCircularDeque object will be instantiated and called as such: + */ +$k = 3; +$obj = new MyCircularDeque($k); +$ret_1 = $obj->insertLast(1); +$ret_2 = $obj->insertLast(2); +$ret_3 = $obj->insertFront(3); +$ret_4 = $obj->insertFront(4); +$ret_5 = $obj->getRear(); +$ret_6 = $obj->isFull(); +$ret_7 = $obj->deleteLast(); +$ret_8 = $obj->insertFront(4); +$ret_9 = $obj->getFront(); +$ret_10 = $obj->isEmpty(); +var_dump($ret_1, $ret_2, $ret_3, $ret_4, $ret_5, $ret_6, $ret_7, $ret_8, $ret_9, $ret_10); From a9ccf395cb4c8c0cbf1f68315d9060aab263ca3d Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 19 Nov 2020 12:22:17 +0800 Subject: [PATCH 007/192] =?UTF-8?q?=E6=8E=A5=E9=9B=A8=E6=B0=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week1/42.trapping-rain-water.php | 96 ++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 Week1/42.trapping-rain-water.php diff --git a/Week1/42.trapping-rain-water.php b/Week1/42.trapping-rain-water.php new file mode 100644 index 00000000..1d7b63af --- /dev/null +++ b/Week1/42.trapping-rain-water.php @@ -0,0 +1,96 @@ +isEmpty() && $height[$stack->top()] <= $height[$i]) { + $prev = $stack->pop(); + if ($stack->isEmpty()) break; + $boundX = $i - $stack->top() - 1; + $boundY = min($height[$i], $height[$stack->top()]) - $height[$prev]; + $ret += $boundX * $boundY; + } + $stack->push($i); + } + return $ret; + } + + /** + * 二、动态规划 O(n) O(n) + * @param Integer[] $height + * @return Integer + */ + function trap1($height) + { + $dpL = []; + $maxL = 0; + $dpR = []; + $maxR = 0; + $count = count($height); + $ret = 0; + for ($i = 0; $i < $count; $i++) { + if ($height[$i] > $maxL) { + $maxL = $height[$i]; + } + $dpL[$i] = $maxL; + } + for ($i = $count - 1; $i >= 0; $i--) { + if ($height[$i] > $maxR) { + $maxR = $height[$i]; + } + $dpR[$i] = $maxR; + } + + for ($i = 1; $i < $count - 1; $i++) { + $ret += min($dpL[$i], $dpR[$i]) - $height[$i]; + } + + return $ret; + } + + + /** + * 三、双指针 O(n) O(1) + * @param Integer[] $height + * @return Integer + */ + function trap($height) + { + $count = count($height); + $pL = 0; + $pR = $count - 1; + + $ret = 0; + while ($pL < $pR) { + $minHeight = min($height[$pL], $height[$pR]); + if ($minHeight == $height[$pL]) { + while ($pL < $pR && $height[$pL] <= $minHeight) { + $ret += $minHeight - $height[$pL]; + $pL++; + } + } else { + while ($pL < $pR && $height[$pR] <= $minHeight) { + $ret += $minHeight - $height[$pR]; + $pR--; + } + } + } + return $ret; + } +} + +$in = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]; +$s = new Solution(); +$ret = $s->trap($in); +print_r($ret); \ No newline at end of file From ecf1b4c3fd1f99be3bce60d2a4783c8c6ad6e63f Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 19 Nov 2020 16:15:58 +0800 Subject: [PATCH 008/192] =?UTF-8?q?=E5=8A=A0=E4=B8=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week1/66.plus-one.php | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Week1/66.plus-one.php diff --git a/Week1/66.plus-one.php b/Week1/66.plus-one.php new file mode 100644 index 00000000..b82a39ed --- /dev/null +++ b/Week1/66.plus-one.php @@ -0,0 +1,33 @@ += 0; $i--) { + if($digits[$i] < 9) { + $digits[$i]++; + return $digits; + } + $digits[$i] = 0; + } + array_unshift($digits, 1); + return $digits; + } +} + +$in = [0,0]; +$in = [9]; +$in = [1, 9, 9, 9]; +$s = new Solution(); +$ret = $s->plusOne($in); +print_r($ret); + + From 824708a6619b16f387d5bf20902be4c3dd8df961 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 19 Nov 2020 17:21:15 +0800 Subject: [PATCH 009/192] =?UTF-8?q?=E7=A7=BB=E5=8A=A8=E9=9B=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week1/283.move-zeroes.php | 52 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Week1/283.move-zeroes.php diff --git a/Week1/283.move-zeroes.php b/Week1/283.move-zeroes.php new file mode 100644 index 00000000..d98c8bf8 --- /dev/null +++ b/Week1/283.move-zeroes.php @@ -0,0 +1,52 @@ +moveZeroes($in); +print_r($in); From 93ff4d741440974be2c6512e9320d45e7dcba85e Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 19 Nov 2020 17:27:25 +0800 Subject: [PATCH 010/192] =?UTF-8?q?=E4=B8=A4=E6=95=B0=E4=B9=8B=E5=92=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week1/1.two-sum.php | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Week1/1.two-sum.php diff --git a/Week1/1.two-sum.php b/Week1/1.two-sum.php new file mode 100644 index 00000000..3453aa77 --- /dev/null +++ b/Week1/1.two-sum.php @@ -0,0 +1,17 @@ + Date: Thu, 19 Nov 2020 19:28:21 +0800 Subject: [PATCH 011/192] =?UTF-8?q?=E5=90=88=E5=B9=B6=E4=B8=A4=E4=B8=AA?= =?UTF-8?q?=E6=9C=89=E5=BA=8F=E9=93=BE=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week1/21.merge-two-sorted-lists.php | 65 +++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 Week1/21.merge-two-sorted-lists.php diff --git a/Week1/21.merge-two-sorted-lists.php b/Week1/21.merge-two-sorted-lists.php new file mode 100644 index 00000000..6dd3e212 --- /dev/null +++ b/Week1/21.merge-two-sorted-lists.php @@ -0,0 +1,65 @@ +val = $val; + $this->next = $next; + } +} + +class Solution +{ + + /** + * 一、递归 O(m+n) O(m+n) + * @param ListNode $l1 + * @param ListNode $l2 + * @return ListNode + */ + function mergeTwoLists2($l1, $l2) + { + if (!$l1) { + return $l2; + } elseif (!$l2) { + return $l1; + }elseif($l1->val <= $l2->val){ + $l1->next = $this->mergeTwoLists($l1->next, $l2); + return $l1; + }else{ + $l2->next = $this->mergeTwoLists($l2->next, $l1); + return $l2; + } + } + + /** + * 一、迭代 O(m+n) O(1) + * @param ListNode $l1 + * @param ListNode $l2 + * @return ListNode + */ + function mergeTwoLists($l1, $l2) + { + $preHead = new ListNode(-1); + $prev = $preHead; + while ($l1 && $l2) { + if ($l1->val <= $l2->val) { + $prev->next = $l1; + $l1 = $l1->next; + }else{ + $prev->next = $l2; + $l2 = $l2->next; + } + $prev = $prev->next; + } + $prev->next = $l1 ? $l1 : $l2; + return $preHead->next; + } +} \ No newline at end of file From 16c69fae1c1911e122d41cde5e3b335149945d71 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Fri, 20 Nov 2020 08:48:33 +0800 Subject: [PATCH 012/192] =?UTF-8?q?=E5=90=88=E5=B9=B6=E4=B8=A4=E4=B8=AA?= =?UTF-8?q?=E6=9C=89=E5=BA=8F=E6=95=B0=E7=BB=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week1/88.merge-sorted-array.php | 48 +++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Week1/88.merge-sorted-array.php diff --git a/Week1/88.merge-sorted-array.php b/Week1/88.merge-sorted-array.php new file mode 100644 index 00000000..c830a441 --- /dev/null +++ b/Week1/88.merge-sorted-array.php @@ -0,0 +1,48 @@ += 0 && $p2 >= 0) { + $nums1[$p0--] = $nums1[$p1] > $nums2[$p2] ? $nums1[$p1--] : $nums2[$p2--]; + } + + while ($p2 >= 0) { + $nums1[$p0--] = $nums2[$p2--]; + } + + } +} + +$in1 = [1, 2, 3, 0, 0, 0]; +$in2 = [2, 5, 6]; +$m = 3; +$n = 3; + +$in1 = [0]; +$in2 = [1]; +$m = 0; +$n = 1; + +$in1 = [-1, 0, 0, 3, 3, 3, 0, 0, 0]; +$in2 = [1, 2, 2]; +$m = 6; +$n = 3; + + +$s = new Solution(); +$out = $s->merge($in1, $m, $in2, $n); +print_r($in1); From 101d8794bfbecd08a03aa6b02e51043df100c66d Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Fri, 20 Nov 2020 09:35:26 +0800 Subject: [PATCH 013/192] =?UTF-8?q?=E4=B8=89=E6=95=B0=E4=B9=8B=E5=92=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week1/15.3sum.php | 53 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Week1/15.3sum.php diff --git a/Week1/15.3sum.php b/Week1/15.3sum.php new file mode 100644 index 00000000..bd56d8e1 --- /dev/null +++ b/Week1/15.3sum.php @@ -0,0 +1,53 @@ + 0) return $ret; + if ($i > 0 && $nums[$i] == $nums[$i - 1]) continue; //注意这个地方一定不要写成 $i-- 死循环 + $l = $i + 1; + $r = $count - 1; + while ($l < $r) { + $sum = $nums[$i] + $nums[$l] + $nums[$r]; + if ($sum < 0) { + $l++; + } elseif ($sum == 0) { + $ret[] = [$nums[$i], $nums[$l], $nums[$r]]; + while ($l < $r && $nums[$l] == $nums[$l + 1]) $l++; + while ($l < $r && $nums[$r] == $nums[$r - 1]) $r--; + $l++; + $r--; + } elseif ($sum > 0) { + $r--; + } + } + } + return $ret; + } +} + + +$in = [-1, 0, 1, 2, -1, -4]; +$s = new Solution(); +$ret = $s->threeSum($in); +print_r($ret); + +/* +[ + [-1, 0, 1], + [-1, -1, 2] +] +*/ + From cd7e35e8175a58a119b7f054b3c9a81487ddedbe Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Fri, 20 Nov 2020 11:14:47 +0800 Subject: [PATCH 014/192] =?UTF-8?q?=E7=88=AC=E6=A5=BC=E6=A2=AF=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week1/70.climbing-stairs.php | 38 ++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Week1/70.climbing-stairs.php diff --git a/Week1/70.climbing-stairs.php b/Week1/70.climbing-stairs.php new file mode 100644 index 00000000..5f1af87b --- /dev/null +++ b/Week1/70.climbing-stairs.php @@ -0,0 +1,38 @@ +climbStairs($in); +print_r($ret); \ No newline at end of file From c4bf0c67424fbc98387d04348bf2f0d4546bbf5f Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Fri, 20 Nov 2020 12:36:15 +0800 Subject: [PATCH 015/192] =?UTF-8?q?=E6=B1=82X=E7=9A=84N=E6=AC=A1=E5=B9=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week1/50.powx-n.php | 63 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Week1/50.powx-n.php diff --git a/Week1/50.powx-n.php b/Week1/50.powx-n.php new file mode 100644 index 00000000..e56b65a3 --- /dev/null +++ b/Week1/50.powx-n.php @@ -0,0 +1,63 @@ +dg($x, -$n); + } else { + return $this->dg($x, $n); + } + } + + function dg($x, $n) + { + if ($n == 0) return 1; + $half = $this->dg($x, $n / 2); + if ($n % 2 == 0) { + return $half * $half; + } else { + return $half * $half * $x; + } + } + + /** + * 二、迭代快速幂 O(logN) O(1) + * @param Float $x + * @param Integer $n + * @return Float + */ + function myPow($x, $n) + { + if ($n < 0) { + return 1 / $this->dd($x, -$n); + } else { + return $this->dd($x, $n); + } + } + + function dd($x,$n) { + if ($n == 0) return 1; + $ret = 1; + while ($n) { + if (($n & 1)) $ret *= $x; + $x *= $x; + $n >>= 1; + } + return $ret; + } +} + +$x = 2; +$n = -2; +$s = new Solution(); +$ret = $s->myPow($x, $n); +print_r($ret); \ No newline at end of file From d62d13b23cea564db7567780648c49a9372db92c Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Fri, 20 Nov 2020 12:42:08 +0800 Subject: [PATCH 016/192] optimize --- Week1/50.powx-n.php | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/Week1/50.powx-n.php b/Week1/50.powx-n.php index e56b65a3..b8729e1c 100644 --- a/Week1/50.powx-n.php +++ b/Week1/50.powx-n.php @@ -11,11 +11,16 @@ class Solution */ function myPow1($x, $n) { +// if ($n < 0) { +// return 1 / $this->dg($x, -$n); +// } else { +// return $this->dg($x, $n); +// } if ($n < 0) { - return 1 / $this->dg($x, -$n); - } else { - return $this->dg($x, $n); + $x = 1 / $x; + $n = -n; } + return $this->dg($x, $n); } function dg($x, $n) @@ -37,11 +42,16 @@ function dg($x, $n) */ function myPow($x, $n) { +// if ($n < 0) { +// return 1 / $this->dd($x, -$n); +// } else { +// return $this->dd($x, $n); +// } if ($n < 0) { - return 1 / $this->dd($x, -$n); - } else { - return $this->dd($x, $n); + $x = 1 / $x; + $n = -$n; } + return $this->dd($x, $n); } function dd($x,$n) { From febb5c251ef974d756a0cec9df70d1dc5c6dc62b Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Fri, 20 Nov 2020 15:46:15 +0800 Subject: [PATCH 017/192] =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2=E7=9B=B8?= =?UTF-8?q?=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week1/415.add-strings.php | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Week1/415.add-strings.php diff --git a/Week1/415.add-strings.php b/Week1/415.add-strings.php new file mode 100644 index 00000000..e1e20d9a --- /dev/null +++ b/Week1/415.add-strings.php @@ -0,0 +1,35 @@ + O(n) O(1) + * @param String $num1 + * @param String $num2 + * @return String + */ + function addStrings($num1, $num2) + { + $p1 = strlen($num1) - 1; + $p2 = strlen($num2) - 1; + $carry = 0; + $ret = ''; + while ($p1 > -1 || $p2 > -1 || $carry != 0) { + $x = $p1 > -1 ? $num1[$p1] : 0; + $y = $p2 > -1 ? $num2[$p2] : 0; + $sum = $x + $y + $carry; + $ret .= $sum % 10; + $carry = floor($sum / 10); + $p1--; + $p2--; + } + return strrev($ret); + } +} + +$a = '56789'; +$b = '1234'; +$s = new Solution(); +$ret = $s->addStrings($a, $b); +print_r($ret); From 18601099b127e1737061917e90b12c0fcc0f3bdd Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Fri, 20 Nov 2020 16:39:21 +0800 Subject: [PATCH 018/192] =?UTF-8?q?=E4=B8=A4=E6=95=B0=E7=9B=B8=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week1/2.add-two-numbers.php | 50 +++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Week1/2.add-two-numbers.php diff --git a/Week1/2.add-two-numbers.php b/Week1/2.add-two-numbers.php new file mode 100644 index 00000000..a0bc777f --- /dev/null +++ b/Week1/2.add-two-numbers.php @@ -0,0 +1,50 @@ +val = $val; + $this->next = $next; + } +} + +class Solution +{ + + /** + * 模拟竖式加法 O(n) O(1) + * @param ListNode $l1 + * @param ListNode $l2 + * @return ListNode + */ + function addTwoNumbers($l1, $l2) + { + $head = $tail = null; + $carry = 0; + while ($l1 || $l2) { + $x = $l1 ? $l1->val : 0; + $y = $l2 ? $l2->val : 0; + $sum = $x + $y + $carry; + $carry = floor($sum / 10); + if (!$tail) { + $head = $tail = new ListNode($sum % 10); + } else { + $tail->next = new ListNode($sum % 10); + $tail = $tail->next; + } + if ($l1) $l1 = $l1->next; + if ($l2) $l2 = $l2->next; + } + if ($carry) { + $tail->next = new ListNode(1); + } + return $head; + } +} \ No newline at end of file From 38cc2d32f601faba044911b968a6bb3e9ef6a9f7 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Fri, 20 Nov 2020 19:46:52 +0800 Subject: [PATCH 019/192] =?UTF-8?q?optimize=20=E4=B8=A4=E6=95=B0=E4=B9=8B?= =?UTF-8?q?=E5=92=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week1/1.two-sum.php | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/Week1/1.two-sum.php b/Week1/1.two-sum.php index 3453aa77..5e4a9969 100644 --- a/Week1/1.two-sum.php +++ b/Week1/1.two-sum.php @@ -4,11 +4,15 @@ * @param Integer $target * @return Integer[] */ -function twoSum($nums, $target) { +function twoSum($nums, $target) +{ $hash = []; - for($i = 0; $i < count($nums);$i++) { - if(array_key_exists($target - $nums[$i],$hash)){ - return [$hash[$target - $nums[$i]],$i]; + for ($i = 0; $i < count($nums); $i++) { +// if(array_key_exists($target - $nums[$i],$hash)){ +// return [$hash[$target - $nums[$i]],$i]; +// } + if (isset($hash[$target - $nums[$i]])) { + return [$hash[$target - $nums[$i]], $i]; } $hash[$nums[$i]] = $i; } From 2e5640ab409ead0606a4f2089f3d5ea56a850e63 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sat, 21 Nov 2020 05:37:14 +0800 Subject: [PATCH 020/192] =?UTF-8?q?=E7=88=AC=E6=A5=BC=E6=A2=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week1/70.climbing-stairs.php | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/Week1/70.climbing-stairs.php b/Week1/70.climbing-stairs.php index 5f1af87b..c9a43766 100644 --- a/Week1/70.climbing-stairs.php +++ b/Week1/70.climbing-stairs.php @@ -20,16 +20,40 @@ function climbStairs1($n) { } /** - * 三、斐波那锲通项公式 + * 二、矩阵快速幂 + * https://blog.csdn.net/xuzengqiang/article/details/7645020 + * https://www.cnblogs.com/liushang0419/archive/2011/10/06/2199722.html + */ + + /** + * 三、斐波那锲通项公式 O(LogN) O(1) + * pow 方法将会用去O(logN)的时间 * @param Integer $n * @return Integer */ - function climbStairs($n) { + function climbStairs3($n) { $sqrt5 = sqrt(5); $fibn = pow((1 + $sqrt5)/2,$n + 1) - pow((1 - $sqrt5)/2,$n + 1); return (int)($fibn / $sqrt5); } + /** + * 四、尾递归 O(n) 若优化O(1) + * 尾递归若优化,空间复杂度可达到o(1),但时间复杂度是o(n) + * @param Integer $n + * @return Integer + */ + function climbStairs($n) + { + return $this->wdg($n, 1, 2); + } + + function wdg($n, $f1, $f2) + { + if ($n < 2) return $f1; //递归终止条件 要到第一个值 + return $this->wdg($n - 1, $f2, $f1 + $f2); + } + } $in = 5; From f829602907250c0c471c48cfed3df8c971b8efad Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sat, 21 Nov 2020 11:36:27 +0800 Subject: [PATCH 021/192] =?UTF-8?q?=E5=8F=8D=E8=BD=AC=E9=93=BE=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week1/206.reverse-linked-list.php | 51 +++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Week1/206.reverse-linked-list.php diff --git a/Week1/206.reverse-linked-list.php b/Week1/206.reverse-linked-list.php new file mode 100644 index 00000000..bfde75d9 --- /dev/null +++ b/Week1/206.reverse-linked-list.php @@ -0,0 +1,51 @@ +val = $val; + } +} + +class Solution +{ + /** + * 一、递归 O(n) O(n) + * @param ListNode $head + * @return ListNode + */ + function reverseList2($head) + { + if (!$head || !$head->next) return $head; + $revNode = $this->reverseList($head->next); + $head->next->next = $head; + $head->next = null; + return $revNode; + } + + /** + * 二、双指针迭代 O(n) O(1) + * @param ListNode $head + * @return ListNode + */ + function reverseList($head) + { + $si = null; //这是尾巴 $fi -> $si + $fi = $head; + while ($fi) { + $tmp = $fi->next; + $fi->next = $si; + $si = $fi; + $fi = $tmp; + } + return $si; + } + +} \ No newline at end of file From bf570c9d2b9b031b1237e43133673efc2b40e60e Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sat, 21 Nov 2020 13:15:27 +0800 Subject: [PATCH 022/192] =?UTF-8?q?optimize=20=E5=88=A0=E9=99=A4=E6=95=B0?= =?UTF-8?q?=E7=BB=84=E4=B8=AD=E9=87=8D=E5=A4=8D=E5=85=83=E7=B4=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week1/26.remove-duplicates-from-sorted-array.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Week1/26.remove-duplicates-from-sorted-array.php b/Week1/26.remove-duplicates-from-sorted-array.php index d5c63425..22a7cd2c 100644 --- a/Week1/26.remove-duplicates-from-sorted-array.php +++ b/Week1/26.remove-duplicates-from-sorted-array.php @@ -12,8 +12,7 @@ function removeDuplicates(&$nums) $i = 0; for ($j = 1; $j < count($nums); $j++) { if ($nums[$j] != $nums[$j - 1]) { - $nums[$i + 1] = $nums[$j]; - $i++; + $nums[--$i] = $nums[$j]; } } return $i + 1; From 854bc7fed301d5b92c27d04e2d86d5bd665d6f8e Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sat, 21 Nov 2020 13:16:15 +0800 Subject: [PATCH 023/192] =?UTF-8?q?=E7=A7=BB=E9=99=A4=E5=85=83=E7=B4=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week1/27.remove-element.php | 57 +++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Week1/27.remove-element.php diff --git a/Week1/27.remove-element.php b/Week1/27.remove-element.php new file mode 100644 index 00000000..d841fc3f --- /dev/null +++ b/Week1/27.remove-element.php @@ -0,0 +1,57 @@ +removeElement($in, $k); +print_r($in); \ No newline at end of file From 1ee3d9ffcc39f8647833cc9f4bf9ce3e61ffd7a6 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sun, 22 Nov 2020 13:49:36 +0800 Subject: [PATCH 024/192] =?UTF-8?q?=E6=9D=A8=E8=BE=89=E4=B8=89=E8=A7=92=20?= =?UTF-8?q?II?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week1/119.pascals-triangle-ii.php | 79 +++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 Week1/119.pascals-triangle-ii.php diff --git a/Week1/119.pascals-triangle-ii.php b/Week1/119.pascals-triangle-ii.php new file mode 100644 index 00000000..d56bd098 --- /dev/null +++ b/Week1/119.pascals-triangle-ii.php @@ -0,0 +1,79 @@ +combination($rowIndex, $k); + } + return $ret; + } + + function combination($c, $k) + { + $ret = 1; + for ($i = 1; $i <= $k; $i++) { + $ret *= ($c - $k + $i) / $i; + } + return $ret; + } + + /** + * 一、动态规划 + * 总的来说就是利用杨辉三角形后一行与前一行的关系。 + * 更新过程为:从倒数第二个元素开始往前更新 它等于原来这个位置的数 + 前一个位置的数, 行[i] = 行[i] + 行[i-1] + * @param Integer $rowIndex + * @return Integer[] + */ + function getRow($rowIndex) + { + $ret = []; + for ($i = 0; $i <= $rowIndex; $i++) { + $ret[$i] = 1; ////行末尾为1 + for ($j = $i; $j > 1; $j--) { + $ret[$j - 1] = $ret[$j - 2] + $ret[$j - 1]; + } + } + return $ret; + } + +} + +$in = 4; +$s = new Solution(); +$out = $s->getRow1($in); +//$out = $s->C(7, 4); +print_r($out); + +/** + * 输入: 3 + * 输出: [1,3,3,1] + */ + From 1528639b8a074f3047870fc42ffaf4ce0747c8fa Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sun, 22 Nov 2020 14:59:10 +0800 Subject: [PATCH 025/192] =?UTF-8?q?=E5=AD=A6=E4=B9=A0=E7=AC=94=E8=AE=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week1/README.md | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/Week1/README.md b/Week1/README.md index 50de3041..6443b055 100644 --- a/Week1/README.md +++ b/Week1/README.md @@ -1 +1,33 @@ -学习笔记 \ No newline at end of file +学习笔记 + +#### 时间与空间复杂度 + +#### 数据结构 +- 数组、链表、跳表 + + 数组 + prepend => O(1) + append => O(1) + lookup => O(1) + insert => O(n) + delete => O(n) + 正常情况下数组的 prepend 操作的时间复杂度是O(n) ,但是可以进行特殊优化到O(1)。 + 采用的方式时申请稍大一些的内存空间,然后再数组最开始预留一部分空间,然后prepend的操作则是把头下标前移一个位置即可。 + + 链表 + prepend => O(1) + append => O(1) + lookup => O(n) 随机访问 + insert => O(1) + delete => O(1) + + 3.跳表 + 跳表的空间复杂度是O(n, 实际节点肯定是要比原节点要多的 + 再跳表中查询任意数据的时间复杂度就是O(logn) + +- 栈、队列、双端队列、优先队列 + + + +`测试` + red \ No newline at end of file From 67036b0a730f946e694a485416e9fd988395c455 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Mon, 23 Nov 2020 08:57:31 +0800 Subject: [PATCH 026/192] =?UTF-8?q?=E4=B8=A4=E4=B8=A4=E4=BA=A4=E6=8D=A2?= =?UTF-8?q?=E9=93=BE=E8=A1=A8=E4=B8=AD=E7=9A=84=E8=8A=82=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week1/24.swap-nodes-in-pairs.php | 57 ++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Week1/24.swap-nodes-in-pairs.php diff --git a/Week1/24.swap-nodes-in-pairs.php b/Week1/24.swap-nodes-in-pairs.php new file mode 100644 index 00000000..8e6b315b --- /dev/null +++ b/Week1/24.swap-nodes-in-pairs.php @@ -0,0 +1,57 @@ +val = $val; + $this->next = $next; + } +} + +class Solution +{ + + /** + * 二、迭代 O(n) O(1) + * @param ListNode $head + * @return ListNode + */ + function swapPairs1($head) + { + $dummyHead = new ListNode(-1); + $dummyHead->next = $head; + $temp = $dummyHead; + while ($temp->next && $temp->next->next) { + $si = $temp->next; + $fi = $temp->next->next; + $temp->next = $fi; + $si->next = $fi->next; + $fi->next = $si; + $temp = $si->next; + } + return $dummyHead->next; + } + + /** + * 二、递归 O(n) O(n) + * @param ListNode $head + * @return ListNode + */ + function swapPairs($head) + { + if (!$head || !$head->next) { + return $head; + } + $newHead = $head->next; + $head->next = $this->swapPairs($newHead->next); + $newHead->next = $head; + return $newHead; + } +} \ No newline at end of file From e26311a70ae7b349d71de5d99e1e09e87bd2d584 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Mon, 23 Nov 2020 11:20:33 +0800 Subject: [PATCH 027/192] =?UTF-8?q?=E4=B8=A4=E4=B8=A4=E4=BA=A4=E6=8D=A2?= =?UTF-8?q?=E9=93=BE=E8=A1=A8=E4=B8=AD=E8=8A=82=E7=82=B9=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=20=E6=A0=88=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week1/24.swap-nodes-in-pairs.php | 43 ++++++++++++++++++++++++++------ 1 file changed, 36 insertions(+), 7 deletions(-) diff --git a/Week1/24.swap-nodes-in-pairs.php b/Week1/24.swap-nodes-in-pairs.php index 8e6b315b..49d1b0c6 100644 --- a/Week1/24.swap-nodes-in-pairs.php +++ b/Week1/24.swap-nodes-in-pairs.php @@ -25,12 +25,12 @@ class Solution */ function swapPairs1($head) { - $dummyHead = new ListNode(-1); - $dummyHead->next = $head; - $temp = $dummyHead; + $dummyHead = new ListNode(-1);//哨兵节点 + $dummyHead->next = $head; //哨兵节点连线 + $temp = $dummyHead; //遍历指针 while ($temp->next && $temp->next->next) { - $si = $temp->next; - $fi = $temp->next->next; + $si = $temp->next; //慢指针 指向第一个节点 + $fi = $temp->next->next; //快指针 指向第二个节点 $temp->next = $fi; $si->next = $fi->next; $fi->next = $si; @@ -40,11 +40,11 @@ function swapPairs1($head) } /** - * 二、递归 O(n) O(n) + * 一、递归 O(n) O(n) * @param ListNode $head * @return ListNode */ - function swapPairs($head) + function swapPairs2($head) { if (!$head || !$head->next) { return $head; @@ -54,4 +54,33 @@ function swapPairs($head) $newHead->next = $head; return $newHead; } + + /** + * 三、栈 O(n) O(1) + * @param ListNode $head + * @return ListNode + */ + function swapPairs($head) + { + if (!$head || !$head->next) { + return $head; + } + $dummyHead = new ListNode(-1); //哨兵节点 + $dummyHead->next = $head; //给哨兵节点连线 + $p = $dummyHead; //慢指针 用来串节点 + $cur = $head; //快指针 用来遍历 + $stack = new SplStack(); + while ($cur && $cur->next) { + $stack->push($cur); + $stack->push($cur->next); + $cur = $cur->next->next; + $p->next = $stack->pop(); + $p = $p->next; + $p->next = $stack->pop(); + $p = $p->next; + } + $p->next = $cur ? $cur : null; //处理尾巴 + return $dummyHead->next; + } + } \ No newline at end of file From b12c615860dbb2f253f06ca2426c6f7e915b9404 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Tue, 24 Nov 2020 08:07:40 +0800 Subject: [PATCH 028/192] =?UTF-8?q?K=E4=B8=AA=E4=B8=80=E7=BB=84=E7=BF=BB?= =?UTF-8?q?=E8=BD=AC=E5=88=97=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week1/25.reverse-nodes-in-k-group.php | 120 ++++++++++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 Week1/25.reverse-nodes-in-k-group.php diff --git a/Week1/25.reverse-nodes-in-k-group.php b/Week1/25.reverse-nodes-in-k-group.php new file mode 100644 index 00000000..7a5fe0c9 --- /dev/null +++ b/Week1/25.reverse-nodes-in-k-group.php @@ -0,0 +1,120 @@ +val = $val; + $this->next = $next; + } +} + +class Solution +{ + + /** + * 4指针模拟 O(n),O(1) + * 其中n为链表的长度。head指针会在[n/k]个结点上停留,每次停留需要进行一次O(k)的翻转操作 + * @param ListNode $head + * @param Integer $k + * @return ListNode + */ + function reverseKGroup1($head, $k) + { + $dummyHead = new ListNode(-1); + $dummyHead->next = $head; + $pre = $dummyHead; + while ($head) { + $tail = $pre; // tail是遍历指针 + for ($i = 0; $i < $k; $i++) { + $tail = $tail->next; + if (!$tail) { + return $dummyHead->next; + } + } + $nextGroupHead = $tail->next; + $arrReverse = $this->reverseLink($head, $tail); + $rhead = $arrReverse[0]; + $rtail = $arrReverse[1]; + //连线 将反转后链表接入原链表 + $pre->next = $rhead; + $rtail->next = $nextGroupHead; + $pre = $rtail; + $head = $rtail->next; + } + return $dummyHead->next; + } + + /** + * 指定头尾双指针反转链表 + * @param $head + * @param $tail + */ + function reverseLink($head, $tail) + { + $newTail = $head; + $si = $tail->next; + while ($si !== $tail) { //两个对象比较时要用三个== 否则val相等时可能判断不出来 如 测试用例[4,8,4] k=3 时出错 + $fi = $head->next; + $head->next = $si; + $si = $head; + $head = $fi; + } + return [$tail, $newTail]; + } + + /** + * 双指针反转链表 + * @param $head + * @param $tail + */ + function reverseLink2($head, $tail) + { + $si = null; + while ($head !== $tail) { + $fi = $head->next; + $head->next = $si; + $si = $head; + $head = $fi; + } + return $head; + } + + /** + * 栈 O(n),O(k) + * @param ListNode $head + * @param Integer $k + * @return ListNode + */ + function reverseKGroup($head, $k) + { + $dummyHead = new ListNode(-1); + $si = $dummyHead; + $stack = new SplStack(); + while (true) { + $count = 0; + $fi = $head; + while ($fi && $count < $k) { + $stack->push($fi); + $fi = $fi->next; + $count++; + } + if ($count != $k) { + $si->next = $head; + break; + } + while (!$stack->isEmpty()) { + $si->next = $stack->pop(); + $si = $si->next; + } + $head = $fi; + } + return $dummyHead->next; + } +} \ No newline at end of file From cc0534abb63fa39d822af6cd5857322f9d577e9d Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Tue, 24 Nov 2020 22:03:27 +0800 Subject: [PATCH 029/192] =?UTF-8?q?=E6=9C=80=E5=B0=8F=E7=9A=84K=E4=B8=AA?= =?UTF-8?q?=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week2/offer40.zui-xiao-de-kge-shu-lcof.php | 142 +++++++++++++++++++++ 1 file changed, 142 insertions(+) create mode 100644 Week2/offer40.zui-xiao-de-kge-shu-lcof.php diff --git a/Week2/offer40.zui-xiao-de-kge-shu-lcof.php b/Week2/offer40.zui-xiao-de-kge-shu-lcof.php new file mode 100644 index 00000000..92e29b88 --- /dev/null +++ b/Week2/offer40.zui-xiao-de-kge-shu-lcof.php @@ -0,0 +1,142 @@ +count() < $k) { + //$pq->insert($arr[$i], $arr[$i]); + $pq->insert($arr[$i]); + } else { + if (!$pq->isEmpty() && $pq->top() > $arr[$i]) { + $pq->extract(); + //$pq->insert($arr[$i],$arr[$i]); + $pq->insert($arr[$i]); + } + } + } + $ret = []; + while ($pq->valid()) { + $ret[] = $pq->current(); + $pq->next();; + } + return $ret; + } + + /** + * 二、php内置排序函数sort 采用的是quikSort O(NLogN) O(LogN) + * @param Integer[] $arr + * @param Integer $k + * @return Integer[] + */ + function getLeastNumbers3($arr, $k) + { + sort($arr); + $ret = []; + for ($i = 0; $i < $k; $i++) { + $ret[] = $arr[$i]; + } + return $ret; + } + + /** + * 三、快排变形 快速搜索 O(N) O(LogN) + * 每次调用 partition 遍历的元素数目都是上一次遍历的 1/2,因此时间复杂度是 N + N/2 + N/4 + ... + N/N = 2N, 因此时间复杂度是 O(N) + * 两种方法的优劣性比较 与堆比较 + * 在面试中,另一个常常问的问题就是这两种方法有何优劣。看起来分治法的快速选择算法的时间、空间复杂度都优于使用堆的方法,但是要注意到快速选择算法的几点局限性: + * 第一,算法需要修改原数组,如果原数组不能修改的话,还需要拷贝一份数组,空间复杂度就上去了。 + * 第二,算法需要保存所有的数据。如果把数据看成输入流的话,使用堆的方法是来一个处理一个,不需要保存数据,只需要保存 k 个元素的最大堆。 + * 而快速选择的方法需要先保存下来所有的数据,再运行算法。当数据量非常大的时候,甚至内存都放不下的时候,就麻烦了。所以当数据量大的时候还是用基于堆的方法比较好。 + * @param Integer[] $arr + * @param Integer $k + * @return Integer[] + */ + function getLeastNumbers($arr, $k) + { + if ($k == 0) return []; + if ($k >= count($arr)) return $arr; + $this->quickSearch($arr, 0, count($arr) - 1, $k - 1); + $ret = []; + for ($i = 0; $i < $k; $i++) { + $ret[] = $arr[$i]; + } + return $ret; + } + + /** + * 快速搜索 + * @param $arr + * @param $l + * @param $h + * @param $k + */ + function quickSearch(&$arr, $l, $h, $k) + { + $m = $this->partition($arr, $l, $h); + if ($m == $k) { + return true; + } elseif ($m < $k) { + $this->quickSearch($arr, $m + 1, $h, $k); + } else { + $this->quickSearch($arr, $l, $m - 1, $k); + } + } + + /** + * 快搜分区返回中枢索引 + * 快排分区,返回下标j,使得比nums[j]小的数都在j的左边,比nums[j]大的数都在j的右边 + * @param $arr + * @param $l + * @param $h + */ + function partition(&$arr, $l, $h) + { + $pivot = $arr[$l]; //每次选取[第]一个元素作为基准 + $i = $l; + $j = $h + 1; + while ($i < $j) { + while ($i < $j && $arr[--$j] > $pivot) ; //从右边找到一个比基准小的数 + while ($i < $j && $arr[++$i] < $pivot) ; //从左边找到一个比基准大的数 + if ($i != $j) $this->swap($arr, $i, $j); + } + if ($l != $j) $this->swap($arr, $l, $j); //基准归位 + return $j; + } + + function swap(&$arr, $i, $j) + { + $arr[$i] += $arr[$j]; + $arr[$j] = $arr[$i] - $arr[$j]; + $arr[$i] = $arr[$i] - $arr[$j]; + } +} + +/* + * 输入:arr = [3,2,1], k = 2 + * 输出:[1,2] 或者 [2,1] + */ +$in = [1, 2, 3, 4]; +$k = 4; +$in = [3, 1, 2, 5, 3, 0, 4, 6]; +$k = 3; +$in = [3, 2, 1]; +$k = 2; +$s = new Solution(); +$ret = $s->getLeastNumbers($in, $k); +//$ret = $s->partition($in, 0, 2); +$s->quickSearch($in, 0, 2, 1); +print_r($in); +print_r($ret); From f4aef74d35052ed9f44feb1a44d87bf9eeabbfef Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 25 Nov 2020 09:26:35 +0800 Subject: [PATCH 030/192] =?UTF-8?q?=E6=AF=8F=E6=97=A5=E6=89=93=E5=8D=A1=20?= =?UTF-8?q?=E7=8C=9C=E6=95=B0=E5=AD=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week2/299.bulls-and-cows.php | 42 ++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Week2/299.bulls-and-cows.php diff --git a/Week2/299.bulls-and-cows.php b/Week2/299.bulls-and-cows.php new file mode 100644 index 00000000..97542c89 --- /dev/null +++ b/Week2/299.bulls-and-cows.php @@ -0,0 +1,42 @@ + 0) $y++; + } + } + return $x . 'A' . $y . 'B'; + } +} + +$in = '1807'; +$k = '7810'; +$in = '1123'; +$k = '0111'; +$s = new Solution(); +$ret = $s->getHint($in, $k); +print_r($ret); +/** + * 输入: secret = "1807", guess = "7810" + * 输出: "1A3B" + * 输入: secret = "1123", guess = "0111" + * 输出: "1A1B" + */ \ No newline at end of file From 698e048633caa56dc699396e99ff2f97c979ea29 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 25 Nov 2020 10:38:28 +0800 Subject: [PATCH 031/192] =?UTF-8?q?=E6=9C=80=E5=B0=8F=E7=9A=84K=E4=B8=AA?= =?UTF-8?q?=E6=95=B0=E5=A2=9E=E5=8A=A0=E8=AE=A1=E6=95=B0=E6=8E=92=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week2/offer40.zui-xiao-de-kge-shu-lcof.php | 29 ++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/Week2/offer40.zui-xiao-de-kge-shu-lcof.php b/Week2/offer40.zui-xiao-de-kge-shu-lcof.php index 92e29b88..bdbcbe1d 100644 --- a/Week2/offer40.zui-xiao-de-kge-shu-lcof.php +++ b/Week2/offer40.zui-xiao-de-kge-shu-lcof.php @@ -64,7 +64,7 @@ function getLeastNumbers3($arr, $k) * @param Integer $k * @return Integer[] */ - function getLeastNumbers($arr, $k) + function getLeastNumbers4($arr, $k) { if ($k == 0) return []; if ($k >= count($arr)) return $arr; @@ -122,6 +122,31 @@ function swap(&$arr, $i, $j) $arr[$j] = $arr[$i] - $arr[$j]; $arr[$i] = $arr[$i] - $arr[$j]; } + + /** + * 四、计数排序 O(N) O(N) + * 数据范围有限时直接计数排序就行了 + * @param Integer[] $arr + * @param Integer $k + * @return Integer[] + */ + function getLeastNumbers($arr, $k) + { + $hashMap = array_fill(0, 10000, 0); + $count = count($arr); + for ($i = 0; $i < $count; $i++) { + $hashMap[$arr[$i]]++; + } + $idx = 0; + $ret = []; + for ($i = 0; $i < count($hashMap); $i++) { + while ($hashMap[$i]-- > 0 && $idx < $k) { + $ret[$idx++] = $i; + } + if($idx == $k) break; + } + return $ret; + } } /* @@ -137,6 +162,6 @@ function swap(&$arr, $i, $j) $s = new Solution(); $ret = $s->getLeastNumbers($in, $k); //$ret = $s->partition($in, 0, 2); -$s->quickSearch($in, 0, 2, 1); +//$s->quickSearch($in, 0, 2, 1); print_r($in); print_r($ret); From fc617d07af62791d74903ebc6b347b7e60600465 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 25 Nov 2020 15:51:39 +0800 Subject: [PATCH 032/192] =?UTF-8?q?=E4=B8=8A=E5=8D=87=E4=B8=8B=E9=99=8D?= =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week2/1370.increasing-decreasing-string.php | 44 +++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Week2/1370.increasing-decreasing-string.php diff --git a/Week2/1370.increasing-decreasing-string.php b/Week2/1370.increasing-decreasing-string.php new file mode 100644 index 00000000..dc7c747f --- /dev/null +++ b/Week2/1370.increasing-decreasing-string.php @@ -0,0 +1,44 @@ + 0) { + $ret .= chr($i + ord('a')); + } + } + for ($j = 25; $j >= 0; $j--) { + if ($hashMap[$j]-- > 0) { + $ret .= chr($j + ord('a')); + } + } + } + return $ret; + } +} + +/** + * 输入:s = "aaaabbbbcccc" + * 输出:"abccbaabccba" + */ + +$in = "aaaabbbbcccc"; +$s = new Solution(); +$ret = $s->sortString($in); +print_r($ret); From 45957df868562cc5b1055a4037a5f2ab79785d22 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 25 Nov 2020 22:28:23 +0800 Subject: [PATCH 033/192] =?UTF-8?q?=E6=95=B0=E7=BB=84=E4=B8=AD=E7=AC=ACK?= =?UTF-8?q?=E4=B8=AA=E6=9C=80=E5=A4=A7=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week2/215.kth-largest-element-in-an-array.php | 160 ++++++++++++++++++ 1 file changed, 160 insertions(+) create mode 100644 Week2/215.kth-largest-element-in-an-array.php diff --git a/Week2/215.kth-largest-element-in-an-array.php b/Week2/215.kth-largest-element-in-an-array.php new file mode 100644 index 00000000..e504b09d --- /dev/null +++ b/Week2/215.kth-largest-element-in-an-array.php @@ -0,0 +1,160 @@ +buildHeap($nums, $heapSize); + for ($i = $count - 1; $i > $count - $k; $i--) { + $this->swap($nums, $i, 0); + $heapSize--; + $this->maxHeapify($nums, 0, $heapSize); + } + return $nums[0]; + } + + public function buildHeap(&$arr, $heapSize) + { + for ($i = floor($heapSize / 2); $i >= 0; $i--) { + $this->maxHeapify($arr, $i, $heapSize); + } + } + + /** + * 堆化 + * @param $arr + * @param $i + * @param $heapSize + */ + function maxHeapify(&$arr, $i, $heapSize) + { + $l = 2 * $i + 1; + $r = 2 * $i + 2; + $max = $i; + if ($l < $heapSize && $arr[$l] > $arr[$max]) { //注意这里的$max可不能用$i + $max = $l; + } + if ($r < $heapSize && $arr[$r] > $arr[$max]) { + $max = $r; + } + if ($i != $max) { + $this->swap($arr, $i, $max); + $this->maxHeapify($arr, $max, $heapSize); + } + } + + /** + * 一、内置堆 O(NLogN) O(K) + * 利用内置大根堆或者优先队列实现 + * @param Integer[] $nums + * @param Integer $k + * @return Integer + */ + function findKthLargest2($nums, $k) + { + //$maxHeap = new SplMaxHeap(); + $maxHeap = new SplPriorityQueue(); + for ($i = 0; $i < count($nums); $i++) { + //$maxHeap->insert($nums[$i]); + $maxHeap->insert($nums[$i], $nums[$i]); + } + for ($j = 0; $j < $k - 1; $j++) { + $maxHeap->next(); + } + return $maxHeap->current(); + } + + /** + * 一、内置堆 O(NLogK) O(K) + * 利用内置小根堆实现 + * @param Integer[] $nums + * @param Integer $k + * @return Integer + */ + function findKthLargest3($nums, $k) + { + $heap = new SplMinHeap(); + foreach ($nums as $value) { + if ($heap->count() < $k) { + $heap->insert($value); + } elseif ($value > $heap->top()) { + $heap->extract(); + $heap->insert($value); + } + } + return $heap->top(); + } + + /** + * 二、快排变形 O(N) O(LogN) + * @param Integer[] $nums + * @param Integer $k + * @return Integer + */ + function findKthLargest($nums, $k) + { + $ret = $this->quickSearch($nums, 0, count($nums), $k - 1); + return $ret; + } + + function quickSearch(&$arr, $l, $h, $k) + { + $m = $this->partition($arr, $l, $h, $k); + if ($m == $k) { + return $arr[$m]; + } elseif ($m < $k) { + return $this->quickSearch($arr, $m + 1, $h, $k); + } else { + return $this->quickSearch($arr, $l, $m - 1, $k); + } + } + + function partition(&$arr, $l, $h) + { + $pivot = $arr[$l]; + $i = $l; + $j = $h + 1; + while ($i < $j) { + while ($i < $j && $arr[--$j] < $pivot) ; + while ($i < $j && $arr[++$i] > $pivot) ; + if ($i != $j) { + $this->swap($arr, $i, $j); + } + } + if ($l != $j) { + $this->swap($arr, $l, $j); + } + return $j; + } + + function swap(&$arr, $i, $j) + { + $arr[$i] += $arr[$j]; + $arr[$j] = $arr[$i] - $arr[$j]; + $arr[$i] = $arr[$i] - $arr[$j]; + } +} + +/** + * 输入: [3,2,1,5,6,4] 和 k = 2 + * 输出: 5 + * 输入: [3,2,3,1,2,4,5,5,6] 和 k = 4 + * 输出: 4 + */ +$in = [2, 1]; +$k = 2; +$in = [3, 2, 1, 5, 6, 4]; +$k = 2; +$s = new Solution(); +$ret = $s->findKthLargest1($in, $k); +//$ret = $s->partition($in, 0, 5); +print_r($ret); \ No newline at end of file From 9f67df725314cc4d45802758ecd7f0382ea6c159 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 26 Nov 2020 12:34:16 +0800 Subject: [PATCH 034/192] =?UTF-8?q?=E8=AE=BE=E8=AE=A1=E5=BE=AA=E7=8E=AF?= =?UTF-8?q?=E9=98=9F=E5=88=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week2/622.design-circular-queue.php | 109 ++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 Week2/622.design-circular-queue.php diff --git a/Week2/622.design-circular-queue.php b/Week2/622.design-circular-queue.php new file mode 100644 index 00000000..f15cbfce --- /dev/null +++ b/Week2/622.design-circular-queue.php @@ -0,0 +1,109 @@ +capacity = $k; + $this->count = 0; + $this->queue = []; + $this->headIndex = 0; + } + + /** + * Insert an element into the circular queue. Return true if the operation is successful. + * @param Integer $value + * @return Boolean + */ + function enQueue($value) + { + if ($this->isFull()) { + return false; + } + $tailIndex = ($this->headIndex + $this->count) % $this->capacity; + $this->count++; //这一行需要计算尾索引后再增加 考虑 count = capatity - 1 时的情况 + $this->queue[$tailIndex] = $value; + return true; + } + + /** + * Delete an element from the circular queue. Return true if the operation is successful. + * @return Boolean + */ + function deQueue() + { + if ($this->isEmpty()) { + return false; + } + $this->count--; + $this->headIndex = ($this->headIndex + 1) % $this->capacity; + return true; + } + + /** + * Get the front item from the queue. + * @return Integer + */ + function Front() + { + if ($this->isEmpty()) return -1; + return $this->queue[$this->headIndex]; + } + + /** + * Get the last item from the queue. + * @return Integer + */ + function Rear() + { + if ($this->isEmpty()) return -1; + $tailIndex = ($this->headIndex + $this->count - 1) % $this->capacity; + return $this->queue[$tailIndex]; + } + + /** + * Checks whether the circular queue is empty or not. + * @return Boolean + */ + function isEmpty() + { + return $this->count == 0; + } + + /** + * Checks whether the circular queue is full or not. + * @return Boolean + */ + function isFull() + { + return $this->count == $this->capacity; + } +} + +/** + * Your MyCircularQueue object will be instantiated and called as such: + * $obj = MyCircularQueue($k); + * $ret_1 = $obj->enQueue($value); + * $ret_2 = $obj->deQueue(); + * $ret_3 = $obj->Front(); + * $ret_4 = $obj->Rear(); + * $ret_5 = $obj->isEmpty(); + * $ret_6 = $obj->isFull(); + */ + +/** + * MyCircularQueue circularQueue = new MyCircularQueue(3); // 设置长度为 3 + * circularQueue.enQueue(1); // 返回 true + * circularQueue.enQueue(2); // 返回 true + * circularQueue.enQueue(3); // 返回 true + * circularQueue.enQueue(4); // 返回 false,队列已满 + * circularQueue.Rear(); // 返回 3 + * circularQueue.isFull(); // 返回 true + * circularQueue.deQueue(); // 返回 true + * circularQueue.enQueue(4); // 返回 true + * circularQueue.Rear(); // 返回 4 + */ \ No newline at end of file From 46e683cf3af1f8f05eed040a90438a1308c77b21 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 26 Nov 2020 17:16:27 +0800 Subject: [PATCH 035/192] optimize --- Week2/622.design-circular-queue.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Week2/622.design-circular-queue.php b/Week2/622.design-circular-queue.php index f15cbfce..89c1abc7 100644 --- a/Week2/622.design-circular-queue.php +++ b/Week2/622.design-circular-queue.php @@ -25,8 +25,8 @@ function enQueue($value) return false; } $tailIndex = ($this->headIndex + $this->count) % $this->capacity; - $this->count++; //这一行需要计算尾索引后再增加 考虑 count = capatity - 1 时的情况 $this->queue[$tailIndex] = $value; + $this->count++; //这一行需要计算尾索引后再增加 考虑 count = capatity - 1 时的情况 return true; } From 27f540e8588b4a92f16b8bbb31371dc64b1f42b6 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 26 Nov 2020 17:17:02 +0800 Subject: [PATCH 036/192] =?UTF-8?q?=E9=87=8D=E5=86=99=E8=AE=BE=E8=AE=A1?= =?UTF-8?q?=E5=BE=AA=E7=8E=AF=E9=98=9F=E5=88=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week2/641.design-circular-deque2.php | 136 +++++++++++++++++++++++++++ 1 file changed, 136 insertions(+) create mode 100644 Week2/641.design-circular-deque2.php diff --git a/Week2/641.design-circular-deque2.php b/Week2/641.design-circular-deque2.php new file mode 100644 index 00000000..8be25577 --- /dev/null +++ b/Week2/641.design-circular-deque2.php @@ -0,0 +1,136 @@ +deque = []; + $this->count = 0; + $this->capacity = $k; + $this->front = 0; + $this->rear = 0; //与循环单向队列相比多增加了一个尾部指针 + } + + /** + * Adds an item at the front of Deque. Return true if the operation is successful. + * @param Integer $value + * @return Boolean + */ + function insertFront($value) + { + if ($this->isFull()) { + return false; + } + $this->front = ($this->front - 1 + $this->capacity) % $this->capacity; + $this->deque[$this->front] = $value; //向前移动一个位置再插值 + $this->count++; + return true; + } + + /** + * Adds an item at the rear of Deque. Return true if the operation is successful. + * @param Integer $value + * @return Boolean + */ + function insertLast($value) + { + if ($this->isFull()) { + return false; + } + $this->deque[$this->rear] = $value; + $this->rear = ($this->rear + 1) % $this->capacity; //先插值再向后移动一个位置 + $this->count++; + return true; + } + + /** + * Deletes an item from the front of Deque. Return true if the operation is successful. + * @return Boolean + */ + function deleteFront() + { + if ($this->isEmpty()) { + return false; + } + $this->front = ($this->front + 1) % $this->capacity; + $this->count--; + return true; + } + + /** + * Deletes an item from the rear of Deque. Return true if the operation is successful. + * @return Boolean + */ + function deleteLast() + { + if ($this->isEmpty()) { + return false; + } + $this->rear = ($this->rear - 1 + $this->capacity) % $this->capacity; + $this->count--; + return true; + } + + /** + * Get the front item from the deque. + * @return Integer + */ + function getFront() + { + if ($this->isEmpty()) return -1; + return $this->deque[$this->front]; + } + + /** + * Get the last item from the deque. + * @return Integer + */ + function getRear() + { + if ($this->isEmpty()) return -1; + return $this->deque[($this->rear - 1 + $this->capacity) % $this->capacity]; + } + + /** + * Checks whether the circular deque is empty or not. + * @return Boolean + */ + function isEmpty() + { + return $this->count == 0; + } + + /** + * Checks whether the circular deque is full or not. + * @return Boolean + */ + function isFull() + { + return $this->count == $this->capacity; + } +} + +/** + * Your MyCircularDeque object will be instantiated and called as such: + */ +$k = 3; +$obj = new MyCircularDeque($k); +$ret_1 = $obj->insertLast(1); +print_r($obj); +$ret_2 = $obj->insertLast(2); +print_r($obj); +$ret_3 = $obj->insertFront(3); +print_r($obj); +$ret_4 = $obj->insertFront(4); +print_r($obj); +$ret_5 = $obj->getRear(); +$ret_6 = $obj->isFull(); +$ret_7 = $obj->deleteLast(); +$ret_8 = $obj->insertFront(4); +$ret_9 = $obj->getFront(); +$ret_10 = $obj->isEmpty(); +var_dump($ret_1, $ret_2, $ret_3, $ret_4, $ret_5, $ret_6, $ret_7, $ret_8, $ret_9, $ret_10); From 00894541a51e20af41d4c589bab1b61e6c8428d0 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Fri, 27 Nov 2020 18:51:23 +0800 Subject: [PATCH 037/192] =?UTF-8?q?=E5=89=8DK=E4=B8=AA=E9=AB=98=E9=A2=91?= =?UTF-8?q?=E5=85=83=E7=B4=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week2/347.top-k-frequent-elements.php | 155 ++++++++++++++++++++++++++ 1 file changed, 155 insertions(+) create mode 100644 Week2/347.top-k-frequent-elements.php diff --git a/Week2/347.top-k-frequent-elements.php b/Week2/347.top-k-frequent-elements.php new file mode 100644 index 00000000..d4a10b9a --- /dev/null +++ b/Week2/347.top-k-frequent-elements.php @@ -0,0 +1,155 @@ + $val) { + if ($pg->count() < $k) { + $pg->insert([$val, $key]); + } else { + if (!$pg->isEmpty() && $val > $pg->top()[0]) { + $pg->extract(); + $pg->insert([$val, $key]); + } + } + } + $ret = []; + while (!$pg->isEmpty()) { + $ret[] = $pg->current()[1]; + $pg->next(); + } + return $ret; + } + + /** + * 二、计数排序(桶排序) O(N) O(N) + * @param Integer[] $nums + * @param Integer $k + * @return Integer[] + */ + function topKFrequent2($nums, $k) + { + $hash = []; + for ($i = 0; $i < count($nums); $i++) { + $hash[$nums[$i]]++; + } + $bucket = array_fill(0, count($nums) + 1, []); //初始化桶 + foreach ($hash as $key => $val) { + $bucket[$val][] = $key; + } + $ret = []; + for ($i = count($nums); $i >= 0 && count($ret) < $k; $i--) { + if (!empty($bucket[$i])) { + $ret = array_merge($ret, $bucket[$i]); + } + } + return $ret; + } + + /** + * 三、快排变形 O(N) O(N) + * @param Integer[] $nums + * @param Integer $k + * @return Integer[] + */ + function topKFrequent3($nums, $k) + { + $hash = []; + for ($i = 0; $i < count($nums); $i++) { + $hash[$nums[$i]]++; + } + $arr = []; + foreach ($hash as $key => $val) { + $arr[] = [$key, $val]; + } + $this->quickSearch($arr, 0, count($arr) - 1, $k - 1); + $ret = []; + for ($i = 0; $i < $k; $i++) { + $ret[] = $arr[$i][0]; + } + return $ret; + } + + function quickSearch(&$arr, $l, $h, $k) + { + $m = $this->partition($arr, $l, $h, $k); + if ($m == $k) { + return true; + } elseif ($m > $k) { + $this->quickSearch($arr, $l, $m - 1, $k); + } else { + $this->quickSearch($arr, $m + 1, $h, $k); + } + } + + function partition(&$arr, $l, $h) + { + $pivot = $arr[$l][1]; + $i = $l; + $j = $h + 1; + while ($i < $j) { + while ($i < $j && $arr[--$j][1] < $pivot) ; //这个地方一定要右边的先走, 因为对于00,这种写法上面给j加1了得给机会让它回来 + while ($i < $j && $arr[++$i][1] > $pivot) ; + if ($i != $j) { + $this->swap($arr, $i, $j); + } + } + if ($j != $l) { + $this->swap($arr, $l, $j); + } + return $j; + } + + function swap(&$arr, $i, $j) + { + $tmp = $arr[$j]; + $arr[$j] = $arr[$i]; + $arr[$i] = $tmp; + } +} + +/** + * 输入: nums = [1,1,1,2,2,3], k = 2 + * 输出: [1,2] + */ +$nums = [1, 2]; +$k = 2; +$nums = [-1, -1]; +$k = 1; +$nums = [1, 1, 1, 2, 2, 3]; +$k = 2; +$nums = [3, 0, 1, 0]; +$k = 1; +$nums = [5,1,-1,-8,-7,8,-5,0,1,10,8,0,-4,3,-1,-1,4,-5,4,-3,0,2,2,2,4,-2,-4,8,-7,-7,2,-8,0,-8,10,8,-8,-2,-9,4,-7,6,6,-1,4,2,8,-3,5,-9,-3,6,-8,-5,5,10,2,-5,-1,-5,1,-3,7,0,8,-2,-3,-1,-5,4,7,-9,0,2,10,4,4,-4,-1,-1,6,-8,-9,-1,9,-9,3,5,1,6,-1,-2,4,2,4,-6,4,4,5,-5]; +$k = 7; +$nums = [5,1,-1,-8,-7,8,-5,0,1,10,8,0,-4,3,-1]; +$k = 1; +$s = new Solution(); +$ret = $s->topKFrequent3($nums, $k); +print_r($ret); +//$arr = [ +// [5, 5], +// [1, 4], +// [-1, 10], +// [-8, 6], +// [-7, 4], +//]; +//$ret = $s->quickSearch($arr, 0, 4, 3); +//print_r($arr); +//print_r($ret); +//$ret = $s->partition($arr, 0, 0); +//print_r($arr); +//print_r($ret); From bdfc179acfac6ae56be6ac310a0772f561787c56 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Fri, 27 Nov 2020 20:06:54 +0800 Subject: [PATCH 038/192] =?UTF-8?q?=E4=B8=A4=E4=B8=AA=E6=95=B0=E7=BB=84?= =?UTF-8?q?=E7=9A=84=E4=BA=A4=E9=9B=86II?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week2/350.intersection-of-two-arrays-ii.php | 74 +++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 Week2/350.intersection-of-two-arrays-ii.php diff --git a/Week2/350.intersection-of-two-arrays-ii.php b/Week2/350.intersection-of-two-arrays-ii.php new file mode 100644 index 00000000..1c5bf160 --- /dev/null +++ b/Week2/350.intersection-of-two-arrays-ii.php @@ -0,0 +1,74 @@ +intersect($nums2, $nums1); + } + for ($i = 0; $i < $count1; $i++) { + $hash[$nums1[$i]]++; + } + for ($j = 0; $j < $count2; $j++) { + $v = $nums2[$j]; + if (isset($hash[$v])) { + $ret[] = $v; + if (--$hash[$v] == 0) { + unset($hash[$v]); + } + } + } + return $ret; + } + + /** + * 二、排序双指针 O(mlogm,nlogn) O(min(m,n)) + * @param Integer[] $nums1 + * @param Integer[] $nums2 + * @return Integer[] + */ + function intersect($nums1, $nums2) + { + sort($nums1); + sort($nums2); + $count1 = count($nums1); + $count2 = count($nums2); + $ret = []; + $i = 0; + $j = 0; + $idx = 0; + while ($i < $count1 && $j < $count2) { + if ($nums1[$i] == $nums2[$j]) { + $ret[$idx] = $nums2[$j]; + $idx++; + $i++; + $j++; + } elseif ($nums1[$i] > $nums2[$j]) { + $j++; + } else { + $i++; + } + } + return $ret; + } +} + +$nums1 = [1, 2, 2, 1]; +$nums2 = [2, 2]; +$nums1 = [4, 5, 9]; +$nums2 = [4, 4, 8, 9, 9]; +$s = new Solution(); +$ret = $s->intersect($nums1, $nums2); +print_r($ret); \ No newline at end of file From fc2108320d029149e0d2926107beeb766441961c Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sat, 28 Nov 2020 16:13:13 +0800 Subject: [PATCH 039/192] =?UTF-8?q?=E5=88=A0=E9=99=A4=E6=9C=80=E5=A4=96?= =?UTF-8?q?=E5=B1=82=E6=8B=AC=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week2/1021.remove-outermost-parentheses.php | 54 +++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Week2/1021.remove-outermost-parentheses.php diff --git a/Week2/1021.remove-outermost-parentheses.php b/Week2/1021.remove-outermost-parentheses.php new file mode 100644 index 00000000..5c24ce94 --- /dev/null +++ b/Week2/1021.remove-outermost-parentheses.php @@ -0,0 +1,54 @@ + 0) { + $str .= $S[$i]; + } + if ($S[$i] == ')' && $count-- > 1) { + $str .= $S[$i]; + } + } + return $str; + } + + /** 栈 O(N) O(N) + * @param String $S + * @return String + */ + function removeOuterParentheses2($S) + { + $str = ''; + $stack = new SplStack(); + for ($i = 0; $i < strlen($S); $i++) { + if ($S[$i] == '(') { + if ($stack->count() > 0) { + $str .= $S[$i]; + } + $stack->push('('); + } + if ($S[$i] == ')') { + if ($stack->count() > 1) { + $str .= $S[$i]; + } + $stack->pop(); + } + } + return $str; + } + +} + +$S = "(()())(())(()(()))"; +$s = new Solution(); +$ret = $s->removeOuterParentheses2($S); +print_r($ret); \ No newline at end of file From cb6ad5b11925337c5de77a524589a122eedc1cb3 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sun, 29 Nov 2020 13:40:06 +0800 Subject: [PATCH 040/192] =?UTF-8?q?=E6=BB=91=E5=8A=A8=E7=AA=97=E5=8F=A3?= =?UTF-8?q?=E6=9C=80=E5=A4=A7=20=E5=A2=9E=E5=8A=A0=E7=89=B9=E6=AE=8A?= =?UTF-8?q?=E6=9D=A1=E4=BB=B6=E5=88=A4=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week1/239.sliding-window-maximum.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Week1/239.sliding-window-maximum.php b/Week1/239.sliding-window-maximum.php index 14b6b4fc..5715e597 100644 --- a/Week1/239.sliding-window-maximum.php +++ b/Week1/239.sliding-window-maximum.php @@ -10,6 +10,7 @@ class Solution */ function maxSlidingWindow($nums, $k) { + if ($k == 0 || empty($nums)) return []; $count = count($nums); $deque = new SplQueue(); $ret = []; @@ -37,8 +38,12 @@ function maxSlidingWindow($nums, $k) $in = [1, 3, -1, -3, 5, 3, 6, 7]; $in = [1, -1]; +$in = []; +$in = [1,3,1,2,0,5]; $k = 3; $k = 1; +$k = 0; +$k = 3; $s = new Solution(); $ret = $s->maxSlidingWindow($in, $k); print_r($ret); \ No newline at end of file From c7baf275f3c6ae27e9a31a0940de6cee5e58ccd5 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sun, 29 Nov 2020 15:48:35 +0800 Subject: [PATCH 041/192] =?UTF-8?q?=E6=BB=91=E5=8A=A8=E7=AA=97=E5=8F=A3?= =?UTF-8?q?=E6=9C=80=E5=A4=A7=E5=80=BC=20=E5=A2=9E=E5=8A=A0=E5=8A=A8?= =?UTF-8?q?=E6=80=81=E8=A7=84=E5=88=92=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week1/239.sliding-window-maximum.php | 40 +++++++++++++++++++++++++--- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/Week1/239.sliding-window-maximum.php b/Week1/239.sliding-window-maximum.php index 5715e597..d6cdf363 100644 --- a/Week1/239.sliding-window-maximum.php +++ b/Week1/239.sliding-window-maximum.php @@ -3,7 +3,8 @@ class Solution { /** - * 一、双端单调队列 O(n) O(k) + * 一、双端单调队列 O(N) O(N) + * 输出数组使用了O(N−k+1) 空间,双向队列使用了O(k) * @param Integer[] $nums * @param Integer $k * @return Integer[] @@ -34,16 +35,49 @@ function maxSlidingWindow($nums, $k) } return $ret; } + + /** + * 二、动态规划 O(N) O(N) + * dp(i,j) = max(dp(i,x) = right[i],dp(x,j) = left[j]) + * @param Integer[] $nums + * @param Integer $k + * @return Integer[] + */ + function maxSlidingWindow2($nums, $k) + { + if ($k == 0 || empty($nums)) return []; + $count = count($nums); + $ret = []; + $left[0] = $nums[0]; + $right[$count - 1] = $nums[$count - 1]; + for ($i = 1; $i < $count; $i++) { + if ($i % $k == 0) { + $left[$i] = $nums[$i]; + } else { + $left[$i] = max($nums[$i], $left[$i - 1]); + } + $j = $count - $i - 1; + if (($j + 1) % $k == 0) { + $right[$j] = $nums[$j]; + } else { + $right[$j] = max($nums[$j], $right[$j + 1]); + } + } + for ($i = 0; $i < $count - $k + 1; $i++) { + $ret[] = max($right[$i], $left[$i + $k - 1]); + } + return $ret; + } } $in = [1, 3, -1, -3, 5, 3, 6, 7]; $in = [1, -1]; $in = []; -$in = [1,3,1,2,0,5]; +$in = [1, 3, 1, 2, 0, 5]; $k = 3; $k = 1; $k = 0; $k = 3; $s = new Solution(); -$ret = $s->maxSlidingWindow($in, $k); +$ret = $s->maxSlidingWindow2($in, $k); print_r($ret); \ No newline at end of file From a3b53b7fc81fd88ffc773c37dabfbd761b9f0e41 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sun, 29 Nov 2020 17:55:20 +0800 Subject: [PATCH 042/192] fixed --- Week2/README.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/Week2/README.md b/Week2/README.md index 50de3041..2b82e926 100644 --- a/Week2/README.md +++ b/Week2/README.md @@ -1 +1,9 @@ -学习笔记 \ No newline at end of file +学习笔记 + +#### 数据结构 + +- 树、二叉树、二叉搜索树 + +- 堆、图 + +本周大部分时间在学习堆这种数据结构和相关题目 树和图的题目还没有时间来得及练习 \ No newline at end of file From 731a2c840060dfa2853dbc615a42127d0c2bd7e1 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Mon, 30 Nov 2020 11:01:13 +0800 Subject: [PATCH 043/192] Fizz Buzz --- Week2/412.fizz-buzz.php | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Week2/412.fizz-buzz.php diff --git a/Week2/412.fizz-buzz.php b/Week2/412.fizz-buzz.php new file mode 100644 index 00000000..09d6359a --- /dev/null +++ b/Week2/412.fizz-buzz.php @@ -0,0 +1,37 @@ + 'Fizz', '5' => 'Buzz',]; + $ret = []; + for ($i = 1; $i <= $n; $i++) { + $str = ''; + foreach ($map as $key => $val) { + if ($i % $key == 0) { + $str .= $val; + } + } + if(empty($str)){ + $str = (string)$i; + } + $ret[] = $str; + } + return $ret; + } +} + +$s = new Solution(); +$ret = $s->fizzBuzz(20); +print_r($ret); \ No newline at end of file From 956eb10f4221257d3a0b91efdb2e90b7c121227a Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Mon, 30 Nov 2020 11:04:48 +0800 Subject: [PATCH 044/192] remove test --- Week1/README.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/Week1/README.md b/Week1/README.md index 6443b055..66133542 100644 --- a/Week1/README.md +++ b/Week1/README.md @@ -27,7 +27,3 @@ - 栈、队列、双端队列、优先队列 - - -`测试` - red \ No newline at end of file From a9cf7bf7faa9f856c1504128a1629aa4e7a3bd4c Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Mon, 30 Nov 2020 11:07:59 +0800 Subject: [PATCH 045/192] =?UTF-8?q?=E6=9C=AC=E5=91=A8=E4=B8=BB=E8=A6=81?= =?UTF-8?q?=E5=AD=A6=E4=B9=A0=E5=86=85=E5=AE=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week3/README.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Week3/README.md b/Week3/README.md index 50de3041..4e633f02 100644 --- a/Week3/README.md +++ b/Week3/README.md @@ -1 +1,5 @@ -学习笔记 \ No newline at end of file +学习笔记 + +- 泛型递归、树形递归 + +- 分治、回溯(su第4声) \ No newline at end of file From e9250b0e96e08301e00ba65449740aa087e5bc2b Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Mon, 30 Nov 2020 12:26:13 +0800 Subject: [PATCH 046/192] =?UTF-8?q?=E5=9B=9E=E6=BA=AF=E7=AC=94=E8=AE=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week3/README.md | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/Week3/README.md b/Week3/README.md index 4e633f02..5f4c99df 100644 --- a/Week3/README.md +++ b/Week3/README.md @@ -2,4 +2,31 @@ - 泛型递归、树形递归 -- 分治、回溯(su第4声) \ No newline at end of file +- 分治、回溯(su第4声) + + - 1.DFS 和回溯算法区别 + + DFS 是一个劲的往某一个方向搜索,而回溯算法建立在 DFS 基础之上的,但不同的是在搜索过程中,达到结束条件后,恢复状态,回溯上一层,再次搜索。因此回溯算法与 DFS 的区别就是有无状态重置 + + - 2.何时使用回溯算法 + + 当问题需要 "回头",以此来查找出所有的解的时候,使用回溯算法。即满足结束条件或者发现不是正确路径的时候(走不通),要撤销选择,回退到上一个状态,继续尝试,直到找出所有解为止 + + - 3.怎么样写回溯算法(从上而下,※代表难点,根据题目而变化) + + ①画出递归树,找到状态变量(回溯函数的参数),这一步非常重要※ + ②根据题意,确立结束条件 + ③找准选择列表(与函数参数相关),与第一步紧密关联※ + ④判断是否需要剪枝 + ⑤作出选择,递归调用,进入下一层 + ⑥撤销选择 + + - 4.回溯问题的类型 + + 类型| 题目链接| + ---| ---| + 子集、组合| 子集、子集 II、组合、组合总和、组合总和 II + 全排列| 全排列、全排列 II、字符串的全排列、字母大小写全排列 + 搜索|解数独、单词搜索、N皇后、分割回文串、二进制手表 + +> 注意:子集、组合与排列是不同性质的概念。子集、组合是无关顺序的,而排列是和元素顺序有关的,如 [1,2] 和 [2,1] 是同一个组合(子集),但 [1,2] 和 [2,1] 是两种不一样的排列!!!!因此被分为两类问题 From 9e8e866254002e3aa5951f253bdc02a543d3bba7 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Mon, 30 Nov 2020 17:05:09 +0800 Subject: [PATCH 047/192] =?UTF-8?q?=E5=AD=90=E9=9B=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week3/78.subsets.php | 123 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 123 insertions(+) create mode 100644 Week3/78.subsets.php diff --git a/Week3/78.subsets.php b/Week3/78.subsets.php new file mode 100644 index 00000000..2a5e354f --- /dev/null +++ b/Week3/78.subsets.php @@ -0,0 +1,123 @@ +dfs($nums, 0, []); + return $res; + } + + /** + * 二、回溯思路二、O(N * 2^N)(一共2^n个状态,每种状态需要O(n)的时间来构造子集) O(N)(递归时栈空间的代价为O(n)) + * 每次看看有几个数能选,然后选一个, + * 每次枚举的选项变少,每次传入子递归的 index 是:当前你选的数的索引+1当前你选的数的索引+1 + * 一直递归到「没有可选的数字」,则进入不了 for 循环,因此进不了递归,整个DFS结束。 + * @param Integer[] $nums + * @return Integer[][] + */ + function subsets2($nums) + { + global $res; + $res = []; //注意全局变量生命周期,否则多用例不能通过,也可以使用类变量来实现 + $this->dfs2($nums, 0, []); + return $res; + } + + /** + * 三、位运算枚举迭代 (N * 2^N)(一共2^n个状态,每种状态需要O(n)的时间来构造子集) O(N)(构造子集使用的临时数组 list 的空间代价) + * 记原序列中元素的总数为 n。原序列中的每个数字 a_i 的状态可能有两种,即「在子集中」和「不在子集中」。 + * 我们用 1 表示「在子集中」,0 表示不在子集中,那么每一个子集可以对应一个长度为 n 的 0/1 序列,第 i 位表示 a_i 是否在子集中。 + * @param Integer[] $nums + * @return Integer[][] + */ + function subsets3($nums) + { + $res = []; + for ($i = 0; $i < (1 << count($nums)); $i++) { + $list = []; + for ($j = 0; $j < count($nums); $j++) { + if ($i & (1 << $j)) { + $list[] = $nums[$j]; + } + } + $res[] = $list; + } + return $res; + } + + /** + * 三、逐个循环枚举 (N * 2^N)(一共2^n个状态,每种状态需要O(n)的时间来构造子集) O(N)(构造子集使用的临时数组 list 的空间代价) + * 记原序列中元素的总数为 n。原序列中的每个数字 a_i 的状态可能有两种,即「在子集中」和「不在子集中」。 + * 我们用 1 表示「在子集中」,0 表示不在子集中,那么每一个子集可以对应一个长度为 n 的 0/1 序列,第 i 位表示 a_i 是否在子集中。 + * @param Integer[] $nums + * @return Integer[][] + */ + function subsets4($nums) + { + $res = [[]]; + for ($i = 0; $i < count($nums); $i++) { + $size = count($res); + for ($j = 0; $j < $size; $j++) { //注意这个地方的size需要再上层写好 否则死循环 + $list = $res[$j]; + $list[] = $nums[$i]; + $res[] = $list; + } + } + return $res; + } + + function dfs($nums, $level, $list) + { + global $res; + if ($level == count($nums)) { + $res[] = $list; + return; + } + $this->dfs($nums, $level + 1, $list); + array_push($list, $nums[$level]); + $this->dfs($nums, $level + 1, $list); + array_pop($list); + } + + /** + */ + function dfs2($nums, $level, $list) + { + global $res; + $res[] = $list; + for ($i = $level; $i < count($nums); $i++) { + array_push($list, $nums[$i]); + $this->dfs2($nums, $i + 1, $list); // level = $i + 1 而不是 $level + 1 下一层 只有剩下的数可选 + array_pop($list); + } + } +} + +/** + * 输入: nums = [1,2,3] + * 输出: + * [ + * [3], + * [1], + * [2], + * [1,2,3], + * [1,3], + * [2,3], + * [1,2], + * [] + * ] + */ +$nums = [1, 2, 3]; +$s = new Solution(); +$ret = $s->subsets4($nums); +print_r($ret); \ No newline at end of file From b9d54c88708860013b2fa75582c2e26bd1734f78 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Mon, 30 Nov 2020 21:33:26 +0800 Subject: [PATCH 048/192] =?UTF-8?q?=E5=AD=90=E9=9B=86II?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week3/90.subsets-ii.php | 112 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 Week3/90.subsets-ii.php diff --git a/Week3/90.subsets-ii.php b/Week3/90.subsets-ii.php new file mode 100644 index 00000000..44d620e8 --- /dev/null +++ b/Week3/90.subsets-ii.php @@ -0,0 +1,112 @@ + 使用过的元素不能重复选取 + * @param Integer[] $nums + * @return Integer[][] + */ + function subsetsWithDup($nums) + { + global $res; + $res = []; + sort($nums); + $this->dfs($nums, 0, []); + return $res; + } + + function dfs($nums, $level, $list) + { + global $res; + $res[] = $list; + for ($i = $level; $i < count($nums); $i++) { + if ($i > $level && $nums[$i] == $nums[$i - 1]) continue; + array_push($list, $nums[$i]); + $this->dfs($nums, $i + 1, $list); + array_pop($list); + } + } + + /** + * 二、循环枚举去重 + * https://leetcode-cn.com/problems/subsets-ii/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by-19/ + * @param Integer[] $nums + * @return Integer[][] + */ + function subsetsWithDup2($nums) + { + $res = [[]]; + $start = 1; //新解位置 + sort($nums); + for ($i = 0; $i < count($nums); $i++) { + $size = count($res); + $ansNew = []; + for ($j = 0; $j < $size; $j++) { + $ansOld = $res[$j]; + if ($i > 0 && $nums[$i] == $nums[$i - 1] && $j < $start) continue; + //print_r('i:' . $i . '|j:' . $j . '|s:' . $start . PHP_EOL); + $ansOld[] = $nums[$i]; + $ansNew[] = $ansOld; + } + $start = count($res); // 更新新解位置 记录的是上一次未加入新解前老解个数 需要增加一个临时数组帮助实现 + $res = array_merge($res, $ansNew); + } + + return $res; + } + + /** + * 三、位运算枚举迭代 + * https://leetcode-cn.com/problems/subsets-ii/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by-19/ + * @param Integer[] $nums + * @return Integer[][] + */ + function subsetsWithDup3($nums) + { + $res = []; + $start = 1; //新解位置 + sort($nums); + for ($i = 0; $i < (1 << count($nums)); $i++) { + $list = []; + $flag = 1; + for ($j = 0; $j < count($nums); $j++) { + //if ((1 & ($i >> $j))) { + if (($i & (1 << $j))) { + //if ($j > 0 && $nums[$j] == $nums[$j - 1] && (($i >> ($j - 1)) & 1) == 0) { + if ($j > 0 && $nums[$j] == $nums[$j - 1] && (($i & (1 << ($j - 1)))) == 0) { + $flag = 0; + continue; + } + $list[] = $nums[$j]; + } + } + if($flag) { + $res[] = $list; + } + } + + return $res; + } + +} + +/** + * 输入: nums = [1,2,2] + * 输出: + *[ + * [2], + * [1], + * [1,2,2], + * [2,2], + * [1,2], + * [] + * ] + */ +$nums = [1, 2, 2]; +$s = new Solution(); +$ret = $s->subsetsWithDup3($nums); +print_r($ret); \ No newline at end of file From 5744917a392a83df7001fcb6afff5c89bfdd3694 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Mon, 30 Nov 2020 23:16:40 +0800 Subject: [PATCH 049/192] =?UTF-8?q?=E5=A4=9A=E6=95=B0=E5=85=83=E7=B4=A0=20?= =?UTF-8?q?=E6=B1=82=E4=BC=97=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week3/169.majority-element.php | 60 ++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Week3/169.majority-element.php diff --git a/Week3/169.majority-element.php b/Week3/169.majority-element.php new file mode 100644 index 00000000..15041759 --- /dev/null +++ b/Week3/169.majority-element.php @@ -0,0 +1,60 @@ +> 1; + foreach ($hashMap as $key => $val) { + if ($val > $limit) { + return $key; + } + } + } + + /** + * 二、排序法 O(NLogN) O(LogN) + * @param Integer[] $nums + * @return Integer + */ + function majorityElement2($nums) + { + sort($nums); + $limit = count($nums) >> 1; + return $nums[$limit]; + } + + /** + * 三、摩尔投票法 O(N) O(1) + * @param Integer[] $nums + * @return Integer + */ + function majorityElement3($nums) + { + $count = 0; + $candidate = null; + for ($i = 0; $i < count($nums); $i++) { + if ($count == 0) { + $candidate = $nums[$i]; + } + if ($candidate == $nums[$i]) { + $count++; + } else { + $count--; + } + } + return $candidate; + } +} + +$nums = [3, 2, 3]; +$s = new Solution(); +$ret = $s->majorityElement3($nums); +print_r($ret); \ No newline at end of file From 32ad8c1e45bba5293555f6229926d0c3ffbcdbb8 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Tue, 1 Dec 2020 10:07:03 +0800 Subject: [PATCH 050/192] =?UTF-8?q?=E5=90=84=E4=BD=8D=E7=9B=B8=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week3/258.add-digits.php | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Week3/258.add-digits.php diff --git a/Week3/258.add-digits.php b/Week3/258.add-digits.php new file mode 100644 index 00000000..9b9b2c3c --- /dev/null +++ b/Week3/258.add-digits.php @@ -0,0 +1,21 @@ +addDigits($num); +print_r($ret); \ No newline at end of file From 06e3d34cf7eea7bb2f05311b6852c2ac65866454 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Tue, 1 Dec 2020 12:34:13 +0800 Subject: [PATCH 051/192] =?UTF-8?q?=E7=94=B5=E8=AF=9D=E5=8F=B7=E7=A0=81?= =?UTF-8?q?=E7=9A=84=E5=AD=97=E6=AF=8D=E7=BB=84=E5=90=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ....letter-combinations-of-a-phone-number.php | 123 ++++++++++++++++++ 1 file changed, 123 insertions(+) create mode 100644 Week3/17.letter-combinations-of-a-phone-number.php diff --git a/Week3/17.letter-combinations-of-a-phone-number.php b/Week3/17.letter-combinations-of-a-phone-number.php new file mode 100644 index 00000000..4d6c24ef --- /dev/null +++ b/Week3/17.letter-combinations-of-a-phone-number.php @@ -0,0 +1,123 @@ + 'abc', + '3' => 'def', + '4' => 'ghi', + '5' => 'jkl', + '6' => 'mno', + '7' => 'pqrs', + '8' => 'tuv', + '9' => 'wxyz', + ]; + $this->dfs($digits, $hashMap, 0, ''); + return $res; + } + + function dfs($digits, $hashMap, $level, $s = '') + { + global $res; + if ($level == strlen($digits)) { + $res[] = $s; + return; + } + $letters = $hashMap[$digits[$level]]; + for ($i = 0; $i < strlen($letters); $i++) { + $this->dfs($digits, $hashMap, $level + 1, $s . $letters[$i]); + } + } + + /** + * 二、回溯解法 O(3^n * 4^m) O(len(S)) + * @param String $digits + * @return String[] + */ + function letterCombinations($digits) + { + global $res; + $res = []; + if (empty($digits)) return $res; + $hashMap = [ + '2' => 'abc', + '3' => 'def', + '4' => 'ghi', + '5' => 'jkl', + '6' => 'mno', + '7' => 'pqrs', + '8' => 'tuv', + '9' => 'wxyz', + ]; + $this->backtrack($digits, $hashMap, 0, ''); + return $res; + } + + function backtrack($digits, $hashMap, $level, $s) + { + global $res; + if ($level == strlen($digits)) { + $res[] = $s; + return; + } + $letters = $hashMap[$digits[$level]]; + for ($i = 0; $i < strlen($letters); $i++) { + $s = $s . $letters[$i]; + $this->dfs($digits, $hashMap, $level + 1, $s); + $s = substr($s, 0, -1); + } + } + + /** + * 三、BFS广度优先搜索 O(3^n * 4^m) O(3^n * 4^m) + * @param String $digits + * @return String[] + */ + function letterCombinations3($digits) + { + $queue = []; + if (empty($digits)) return $queue; + array_push($queue, ''); + $hashMap = [ + '2' => 'abc', + '3' => 'def', + '4' => 'ghi', + '5' => 'jkl', + '6' => 'mno', + '7' => 'pqrs', + '8' => 'tuv', + '9' => 'wxyz', + ]; + for ($i = 0; $i < strlen($digits); $i++) { //BFS层数 + $size = count($queue);//队列当前层节点个数 + for ($j = 0; $j < $size; $j++) { //逐个出队 + $s = array_shift($queue); + $letters = $hashMap[$digits[$i]]; + for ($m = 0; $m < strlen($letters); $m++) { + array_push($queue, $s . $letters[$m]); + } + } + } + return $queue; + } +} + +/** + * 输入:"23" + * 输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. + */ +$digits = '23'; +$s = new Solution(); +$ret = $s->letterCombinations3($digits); +print_r($ret); \ No newline at end of file From fbf8a8bedb41480dd669eea7e4c17e0a22b3109e Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Tue, 1 Dec 2020 12:36:39 +0800 Subject: [PATCH 052/192] =?UTF-8?q?=E7=94=B5=E8=AF=9D=E5=8F=B7=E7=A0=81?= =?UTF-8?q?=E7=9A=84=E5=AD=97=E6=AF=8D=E7=BB=84=E5=90=88=20fixed?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week3/17.letter-combinations-of-a-phone-number.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Week3/17.letter-combinations-of-a-phone-number.php b/Week3/17.letter-combinations-of-a-phone-number.php index 4d6c24ef..0df4aea2 100644 --- a/Week3/17.letter-combinations-of-a-phone-number.php +++ b/Week3/17.letter-combinations-of-a-phone-number.php @@ -74,7 +74,7 @@ function backtrack($digits, $hashMap, $level, $s) $letters = $hashMap[$digits[$level]]; for ($i = 0; $i < strlen($letters); $i++) { $s = $s . $letters[$i]; - $this->dfs($digits, $hashMap, $level + 1, $s); + $this->backtrack($digits, $hashMap, $level + 1, $s); $s = substr($s, 0, -1); } } From 8ef1a5824de6e96c5ad0a8fa48094cd94559345c Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Tue, 1 Dec 2020 18:44:52 +0800 Subject: [PATCH 053/192] =?UTF-8?q?=E7=BB=84=E5=90=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week3/77.combinations.php | 130 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 130 insertions(+) create mode 100644 Week3/77.combinations.php diff --git a/Week3/77.combinations.php b/Week3/77.combinations.php new file mode 100644 index 00000000..b2fbfc21 --- /dev/null +++ b/Week3/77.combinations.php @@ -0,0 +1,130 @@ +backtrack($n, $k, 1, []); + return $res; + } + + function backtrack($n, $k, $level, $list) + { + global $res; + if ($k == count($list)) { //这个地方不能 == $level + $res[] = $list; + return true; + } + /** + * 剪枝 + * 搜索起点的上界 + 接下来要选择的元素个数 - 1 = n + * 接下来要选择的元素个数 = k - path.size() + * 搜索起点的上界 = n - (k - path.size()) + 1 + */ + //for ($j = $level; $j <= ($n - ($k - count($list)) + 1); $j++) { //这是剪枝 + for ($j = $level; $j <= $n; $j++) { + array_push($list, $j); + //print_r('递归之前:' . print_r($list,true)); + $this->backtrack($n, $k, $j + 1, $list); + array_pop($list); + //print_r('递归之后:' . print_r($list,true)); + } + } + + /** + * 二、回溯思路二、 + * 按照每个数选与不选 + * @param Integer $n + * @param Integer $k + * @return Integer[][] + */ + function combine2($n, $k) + { + global $res; + $res = []; + $this->backtrack2($n, $k, 1, []); + return $res; + } + + function backtrack2($n, $k, $level, $list) + { + global $res; + if ($k == 0) { + $res[] = $list; + return; + } + +// if ($level > $n - $k + 1) return; //这种写法稍微难理解一点 +// $this->backtrack2($n, $k, $level + 1, $list); + + if ($level <= $n - $k) { + $this->backtrack2($n, $k, $level + 1, $list); + } + + array_push($list, $level); + $this->backtrack2($n, $k - 1, $level + 1, $list); + array_pop($list); + } + + /** + * 三、回溯思路一、另一种写法 + * 有几个数能选 + * @param Integer $n + * @param Integer $k + * @return Integer[][] + */ + function combine3($n, $k) + { + global $res; + $res = []; + $this->backtrack3($n, $k, 1, []); + return $res; + } + + function backtrack3($n, $k, $level, $list) + { + global $res; + if ($k == 0) { + $res[] = $list; + return; + } + for ($i = $level; $i <= $n - $k + 1; $i++) { //这个地方不剪枝也对 + array_push($list, $i); + $this->backtrack3($n, $k - 1, $i + 1, $list); + array_pop($list); + } + } + + /** + * 还有一种位运算,暂时看不懂 有时间再研究 + * https://leetcode-cn.com/problems/combinations/solution/zu-he-by-leetcode-solution/ + */ +} + +/** + *输入: n = 4, k = 2 + * 输出: + * [ + * [2,4], + * [3,4], + * [2,3], + * [1,2], + * [1,3], + * [1,4], + * ] + */ + +$s = new Solution(); +$ret = $s->combine(4, 2); +print_r($ret); \ No newline at end of file From 1f053ff59c2373bd5f09b63698470fb218f11a70 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Tue, 1 Dec 2020 22:13:55 +0800 Subject: [PATCH 054/192] =?UTF-8?q?=E7=BB=84=E5=90=88=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E5=AD=97=E5=85=B8=E5=BA=8F=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week3/77.combinations.php | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/Week3/77.combinations.php b/Week3/77.combinations.php index b2fbfc21..8435e69f 100644 --- a/Week3/77.combinations.php +++ b/Week3/77.combinations.php @@ -108,8 +108,35 @@ function backtrack3($n, $k, $level, $list) /** * 还有一种位运算,暂时看不懂 有时间再研究 + * 时间复杂度:O([n/k]k) O(k) + * 四、 非递归(字典序法)实现组合型枚举 死磕了一晚上终于懂了一丢丢 + * 因为要保证的是字典序。所以核心是必须要增加,但是又要保证只增加最少。 对于一个二进制序列 左边为高位,右边为低位 从低位往高位看 找到第一个连续的1与其左边的0交换 1右边的所有1全部移到最低位 * https://leetcode-cn.com/problems/combinations/solution/zu-he-by-leetcode-solution/ + * @param Integer $n + * @param Integer $k + * @return Integer[][] */ + function combine4($n, $k) + { + $res = []; + $list = range(1, $k, 1); + $list[$k] = $n + 1; //为什么k的位置要存 n + 1 呢? 因为后面循环比较最后一个值的时候会用到 为什么不是n呢?序列的最后的一个最大值是n 所以哨兵也放比n大的数 + $j = 0; + while ($j < $k) { + $res[] = array_slice($list, 0, $k); + $j = 0; + // 寻找第一个 temp[j] + 1 != temp[j + 1] 的位置 t + // 我们需要把 [0, t - 1] 区间内的每个位置重置成 [1, t] //这就是序列一开始的样子么 看下5,3序列的图 就明白了 + while ($j < $k && $list[$j] + 1 == $list[$j + 1]) { + $list[$j] = $j + 1; // + $j++; + } + // j 是第一个 temp[j] + 1 != temp[j + 1] 的位置 + $list[$j]++; + } + + return $res; + } } /** @@ -126,5 +153,5 @@ function backtrack3($n, $k, $level, $list) */ $s = new Solution(); -$ret = $s->combine(4, 2); +$ret = $s->combine4(5, 3); print_r($ret); \ No newline at end of file From 0621b6787327efcf251bf4c0fb5b2b800250392c Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Tue, 1 Dec 2020 23:29:09 +0800 Subject: [PATCH 055/192] =?UTF-8?q?=E5=86=8D=E6=8E=92=E5=BA=8F=E6=95=B0?= =?UTF-8?q?=E7=BB=84=E4=B8=AD=E6=9F=A5=E6=89=BE=E7=AC=AC=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E5=92=8C=E6=9C=80=E5=90=8E=E4=B8=80=E4=B8=AA=E4=BD=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...st-position-of-element-in-sorted-array.php | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Week3/34.find-first-and-last-position-of-element-in-sorted-array.php diff --git a/Week3/34.find-first-and-last-position-of-element-in-sorted-array.php b/Week3/34.find-first-and-last-position-of-element-in-sorted-array.php new file mode 100644 index 00000000..d20ccad0 --- /dev/null +++ b/Week3/34.find-first-and-last-position-of-element-in-sorted-array.php @@ -0,0 +1,51 @@ +binarySearch($nums, $target, true); + $rightIdx = $this->binarySearch($nums, $target, false) - 1; + if ($leftIdx <= $rightIdx && $rightIdx < count($nums) && $nums[$leftIdx] == $target && $nums[$rightIdx] == $target) { + return [$leftIdx, $rightIdx]; + } + return [-1, -1]; + } + + function binarySearch($nums, $target, $lower = false) + { + $l = 0; + $r = count($nums) - 1; + $ans = count($nums); //当nums只有一个数时且就找这个数 + while ($l <= $r) { + $mid = $l + (($r - $l) >> 2); + if ($nums[$mid] > $target || ($lower && $nums[$mid] >= $target)) { + $r = $mid - 1; + $ans = $mid; + } else { + $l = $mid + 1; + } + } + return $ans; + } +} + +/** + * 输入:nums = [5,7,7,8,8,10], target = 8 + * 输出:[3,4] + */ + +$nums = [5, 7, 7, 8, 8, 10]; +$target = 8; +$nums = [1]; +$target = 1; +$s = new Solution(); +$ret = $s->searchRange($nums, $target); +print_r($ret); \ No newline at end of file From bda299d4aa833452b456d8f28a106c60435c1e60 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 2 Dec 2020 10:27:28 +0800 Subject: [PATCH 056/192] =?UTF-8?q?=E6=9C=89=E5=BA=8F=E6=95=B0=E7=BB=84?= =?UTF-8?q?=E4=B8=AD=E6=9F=A5=E6=89=BE=E5=85=83=E7=B4=A0=E7=AC=AC=E4=B8=80?= =?UTF-8?q?=E6=AC=A1=E5=92=8C=E6=9C=80=E5=90=8E=E4=B8=80=E6=AC=A1=E5=87=BA?= =?UTF-8?q?=E7=8E=B0=E7=9A=84=E4=BD=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ....find-first-and-last-position-of-element-in-sorted-array.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Week3/34.find-first-and-last-position-of-element-in-sorted-array.php b/Week3/34.find-first-and-last-position-of-element-in-sorted-array.php index d20ccad0..9a284b94 100644 --- a/Week3/34.find-first-and-last-position-of-element-in-sorted-array.php +++ b/Week3/34.find-first-and-last-position-of-element-in-sorted-array.php @@ -26,7 +26,7 @@ function binarySearch($nums, $target, $lower = false) $ans = count($nums); //当nums只有一个数时且就找这个数 while ($l <= $r) { $mid = $l + (($r - $l) >> 2); - if ($nums[$mid] > $target || ($lower && $nums[$mid] >= $target)) { + if ($nums[$mid] > $target || ($lower && $nums[$mid] == $target)) { $r = $mid - 1; $ans = $mid; } else { From f5921c7bf929bc5129e71a0494aadc1514019e93 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 2 Dec 2020 11:56:44 +0800 Subject: [PATCH 057/192] =?UTF-8?q?=E7=94=B5=E8=AF=9D=E5=8F=B7=E7=A0=81?= =?UTF-8?q?=E7=9A=84=E5=AD=97=E6=AF=8D=E7=BB=84=E5=90=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week3/17.letter-combinations-of-a-phone-number.php | 1 + 1 file changed, 1 insertion(+) diff --git a/Week3/17.letter-combinations-of-a-phone-number.php b/Week3/17.letter-combinations-of-a-phone-number.php index 0df4aea2..9c104b68 100644 --- a/Week3/17.letter-combinations-of-a-phone-number.php +++ b/Week3/17.letter-combinations-of-a-phone-number.php @@ -5,6 +5,7 @@ class Solution /** * 一、递归解法 O(3^n * 4^m) O(len(S)) + * 字符串的问题的特殊之处在于,字符串的拼接生成新对象,因此在这一类问题上没有显示「回溯」的过程 * @param String $digits * @return String[] */ From 0f77c410bc0ef1d82c2aa77942a0d4891c7efaa0 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 2 Dec 2020 15:00:48 +0800 Subject: [PATCH 058/192] =?UTF-8?q?=E5=85=A8=E6=8E=92=E5=88=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week3/46.permutations.php | 93 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 Week3/46.permutations.php diff --git a/Week3/46.permutations.php b/Week3/46.permutations.php new file mode 100644 index 00000000..7ce78c82 --- /dev/null +++ b/Week3/46.permutations.php @@ -0,0 +1,93 @@ +backtrack(count($nums), 0, $list); + return $res; + } + + function backtrack($n, $level, $list) + { + global $res; + if ($level == $n) { + $res[] = $list; + } + for ($i = $level; $i < $n; $i++) { +// print_r('L:' . $level . '|i:' . $i . PHP_EOL); +// print_r($list); + $this->swap($list, $level, $i); + $this->backtrack($n, $level + 1, $list); //注意这个地方是 level 不是 i + $this->swap($list, $level, $i); + } + } + + function swap(&$arr, $i, $j) + { + $temp = $arr[$j]; + $arr[$j] = $arr[$i]; + $arr[$i] = $temp; + } + + /** + * 二、回溯选择法 O(N*N!) O(N) + * @param Integer[] $nums + * @return Integer[][] + */ + function permute2($nums) + { + global $res; + $res = []; + $n = count($nums); + $used = array_fill(0, $n, 0); + $this->backtrack2($nums, $n, $used, 0, []); + return $res; + } + + function backtrack2($nums, $n, $used, $level, $path) + { + global $res; + if ($n == $level) { + $res[] = $path; + return; + } + for ($i = 0; $i < $n; $i++) { + if (!$used[$i]) { + array_push($path, $nums[$i]); + $used[$i] = 1; + $this->backtrack2($nums, $n, $used, $level + 1, $path); + $used[$i] = 0; + array_pop($path); + } + } + } +} + +/** + * 输入: [1,2,3] + * 输出: + * [ + * [1,2,3], + * [1,3,2], + * [2,1,3], + * [2,3,1], + * [3,1,2], + * [3,2,1] + * ] + */ + +$nums = [1, 2, 3]; +$s = new Solution(); +$ret = $s->permute2($nums); +print_r($ret); \ No newline at end of file From 77122be4f45e3a30c37052d4e4069a2064f2b4f9 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 2 Dec 2020 16:36:46 +0800 Subject: [PATCH 059/192] =?UTF-8?q?=E5=85=A8=E6=8E=92=E5=88=97II?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week3/47.permutations-ii.php | 46 ++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Week3/47.permutations-ii.php diff --git a/Week3/47.permutations-ii.php b/Week3/47.permutations-ii.php new file mode 100644 index 00000000..712a737b --- /dev/null +++ b/Week3/47.permutations-ii.php @@ -0,0 +1,46 @@ +backtrack($nums, $n, $used, 0, []); + return $res; + } + + function backtrack($nums, $n, $used, $level, $path) + { + global $res; + if ($level == $n) { + $res[] = $path; + } + for ($i = 0; $i < $n; $i++) { + if ($i > 0 && $nums[$i] == $nums[$i - 1] && !$used[$i - 1]) { //注意第三个条件 + continue; + } + if (!$used[$i]) { + array_push($path, $nums[$i]); + $used[$i] = 1; + $this->backtrack($nums, $n, $used, $level + 1, $path); + array_pop($path); + $used[$i] = 0; + } + } + } +} + +$nums = [1, 1, 2]; +$s = new Solution(); +$ret = $s->permuteUnique($nums); +print_r($ret); \ No newline at end of file From 4b39f95b0c7e5b12425f5a6ca74069fa4cb41d01 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 2 Dec 2020 18:30:26 +0800 Subject: [PATCH 060/192] =?UTF-8?q?=E4=BA=8C=E5=88=86=E6=9F=A5=E6=89=BE?= =?UTF-8?q?=E6=90=9C=E7=B4=A2=E8=BE=B9=E7=95=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...st-position-of-element-in-sorted-array.php | 70 ++++++++++++++++++- 1 file changed, 68 insertions(+), 2 deletions(-) diff --git a/Week3/34.find-first-and-last-position-of-element-in-sorted-array.php b/Week3/34.find-first-and-last-position-of-element-in-sorted-array.php index 9a284b94..1e0cd613 100644 --- a/Week3/34.find-first-and-last-position-of-element-in-sorted-array.php +++ b/Week3/34.find-first-and-last-position-of-element-in-sorted-array.php @@ -35,6 +35,67 @@ function binarySearch($nums, $target, $lower = false) } return $ans; } + + /** + * 寻找左边界 + * @param $nums + * @param $target + */ + function findLeftBorder($nums, $target) + { + $left = 0; + $right = count($nums) - 1; + $leftBorder = -1; + while ($left <= $right) { + $mid = $left + (($right - $left) >> 1); + if ($nums[$mid] >= $target) { + $right = $mid - 1; + $leftBorder = $right; + } else { + $left = $mid + 1; + } + } + return $leftBorder; + } + + /** + * 寻找右边界 + * @param $nums + * @param $target + */ + function findRightBorder($nums, $target) + { + $left = 0; + $right = count($nums) - 1; + $rightBorder = -1; + while ($left <= $right) { + $mid = $left + (($right - $left) >> 1); + if ($nums[$mid] <= $target) { + $left = $mid + 1; + $rightBorder = $left; + } else { + $right = $mid - 1; + } + } + return $rightBorder; + } + + /** + * O(LogN) O(1) + * @param Integer[] $nums + * @param Integer $target + * @return Integer[] + */ + function searchRange2($nums, $target) + { + $leftIdx = $this->findLeftBorder($nums, $target); + $rightIdx = $this->findRightBorder($nums, $target); + if ($leftIdx == -1 && $rightIdx == -1) return [-1, -1]; + if ($leftIdx <= $rightIdx && $nums[$leftIdx + 1] == $target && $nums[$rightIdx - 1] == $target) { + return [$leftIdx + 1, $rightIdx - 1]; + } + return [-1, -1]; + } } /** @@ -42,10 +103,15 @@ function binarySearch($nums, $target, $lower = false) * 输出:[3,4] */ +$nums = [1, 2, 2, 3]; +$target = 2; $nums = [5, 7, 7, 8, 8, 10]; $target = 8; $nums = [1]; $target = 1; $s = new Solution(); -$ret = $s->searchRange($nums, $target); -print_r($ret); \ No newline at end of file +$ret = $s->searchRange2($nums, $target); +print_r($ret); +//$retL = $s->findLeftBorder($nums, $target); +//$retR = $s->findRightBorder($nums, $target); +//print_r([$retL,$retR]);$retR From 79b037d3bd28053f9bb50df421e4b360b1541d4a Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 2 Dec 2020 18:39:33 +0800 Subject: [PATCH 061/192] =?UTF-8?q?debug=20=E4=BA=8C=E5=88=86=E6=90=9C?= =?UTF-8?q?=E7=B4=A2=E8=BE=B9=E7=95=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...-last-position-of-element-in-sorted-array.php | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/Week3/34.find-first-and-last-position-of-element-in-sorted-array.php b/Week3/34.find-first-and-last-position-of-element-in-sorted-array.php index 1e0cd613..a6f95bcd 100644 --- a/Week3/34.find-first-and-last-position-of-element-in-sorted-array.php +++ b/Week3/34.find-first-and-last-position-of-element-in-sorted-array.php @@ -48,9 +48,11 @@ function findLeftBorder($nums, $target) $leftBorder = -1; while ($left <= $right) { $mid = $left + (($right - $left) >> 1); + print_r('L:' . $left . '|R:' . $right . '|m:' . $mid . PHP_EOL); if ($nums[$mid] >= $target) { $right = $mid - 1; $leftBorder = $right; + print_r('LB:' . $leftBorder . PHP_EOL); } else { $left = $mid + 1; } @@ -105,13 +107,13 @@ function searchRange2($nums, $target) $nums = [1, 2, 2, 3]; $target = 2; -$nums = [5, 7, 7, 8, 8, 10]; -$target = 8; $nums = [1]; $target = 1; +$nums = [5, 7, 7, 9, 9, 10]; +$target = 8; $s = new Solution(); -$ret = $s->searchRange2($nums, $target); -print_r($ret); -//$retL = $s->findLeftBorder($nums, $target); -//$retR = $s->findRightBorder($nums, $target); -//print_r([$retL,$retR]);$retR +//$ret = $s->searchRange2($nums, $target); +//print_r($ret); +$retL = $s->findLeftBorder($nums, $target); +$retR = $s->findRightBorder($nums, $target); +print_r([$retL,$retR]); From af935e4466a7f6019d9d3a6381945b43e92e9a37 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 2 Dec 2020 18:43:32 +0800 Subject: [PATCH 062/192] =?UTF-8?q?=E4=BA=8C=E5=88=86=E6=9F=A5=E6=89=BE=20?= =?UTF-8?q?=E8=BE=B9=E7=95=8C=E7=9A=84=E5=87=A0=E7=A7=8D=E6=83=85=E5=86=B5?= =?UTF-8?q?=E9=9C=80=E8=A6=81=E6=B3=A8=E6=84=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...irst-and-last-position-of-element-in-sorted-array.php | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Week3/34.find-first-and-last-position-of-element-in-sorted-array.php b/Week3/34.find-first-and-last-position-of-element-in-sorted-array.php index a6f95bcd..be469963 100644 --- a/Week3/34.find-first-and-last-position-of-element-in-sorted-array.php +++ b/Week3/34.find-first-and-last-position-of-element-in-sorted-array.php @@ -92,11 +92,12 @@ function searchRange2($nums, $target) { $leftIdx = $this->findLeftBorder($nums, $target); $rightIdx = $this->findRightBorder($nums, $target); - if ($leftIdx == -1 && $rightIdx == -1) return [-1, -1]; + if ($leftIdx == -1 && $rightIdx == -1) return [-1, -1]; //针对 target 在数组外部 if ($leftIdx <= $rightIdx && $nums[$leftIdx + 1] == $target && $nums[$rightIdx - 1] == $target) { - return [$leftIdx + 1, $rightIdx - 1]; + return [$leftIdx + 1, $rightIdx - 1]; //针对 target 在数组内部 且存在 + } else { + return [-1, -1]; //针对 target 再数组内部范围 但是target 不在数组中 } - return [-1, -1]; } } @@ -116,4 +117,4 @@ function searchRange2($nums, $target) //print_r($ret); $retL = $s->findLeftBorder($nums, $target); $retR = $s->findRightBorder($nums, $target); -print_r([$retL,$retR]); +print_r([$retL, $retR]); From 19bbedceab8fc57dfd7524eff3beb1b8411d3f40 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 2 Dec 2020 21:15:10 +0800 Subject: [PATCH 063/192] =?UTF-8?q?=E6=9C=89=E6=95=88=E7=9A=84=E5=AD=97?= =?UTF-8?q?=E6=AF=8D=E5=BC=82=E4=BD=8D=E8=AF=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week2/242.valid-anagram.php | 62 +++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Week2/242.valid-anagram.php diff --git a/Week2/242.valid-anagram.php b/Week2/242.valid-anagram.php new file mode 100644 index 00000000..6ea3b1d7 --- /dev/null +++ b/Week2/242.valid-anagram.php @@ -0,0 +1,62 @@ +isAnagram2($a, $b); +var_dump($ret); \ No newline at end of file From fd0493b6def541b8b9ffa04ae7e1dd7f9dd7c422 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 2 Dec 2020 22:18:49 +0800 Subject: [PATCH 064/192] =?UTF-8?q?=E5=AD=97=E6=AF=8D=E5=BC=82=E4=BD=8D?= =?UTF-8?q?=E8=AF=8D=E5=88=86=E7=BB=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week2/49.group-anagrams.php | 56 +++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Week2/49.group-anagrams.php diff --git a/Week2/49.group-anagrams.php b/Week2/49.group-anagrams.php new file mode 100644 index 00000000..3ae0e7be --- /dev/null +++ b/Week2/49.group-anagrams.php @@ -0,0 +1,56 @@ +groupAnagrams2($strs); +print_r($ret); \ No newline at end of file From 4a0a35fe0bb88e564579cf4a53bd58d4d06d98d0 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 2 Dec 2020 23:19:28 +0800 Subject: [PATCH 065/192] =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84?= =?UTF-8?q?=E4=B8=AD=E5=BA=8F=E9=81=8D=E5=8E=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week2/94.binary-tree-inorder-traversal.php | 66 ++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Week2/94.binary-tree-inorder-traversal.php diff --git a/Week2/94.binary-tree-inorder-traversal.php b/Week2/94.binary-tree-inorder-traversal.php new file mode 100644 index 00000000..672e605a --- /dev/null +++ b/Week2/94.binary-tree-inorder-traversal.php @@ -0,0 +1,66 @@ +val = $val; + * $this->left = $left; + * $this->right = $right; + * } + * } + */ +class Solution +{ + + public $ret = []; + + /** + * 一、递归 深度优先搜索 O(n) O(n) + * @param TreeNode $root + * @return Integer[] + */ + function inorderTraversal($root) + { + $this->dfs($root); + return $this->ret; + } + + function dfs($root) + { + if (!$root) return; + $this->dfs($root->left); + $this->ret[] = $root->val; + $this->dfs($root->right); + } + + /** + * 二、栈 栈模拟递归 O(n) O(n) + * @param TreeNode $root + * @return Integer[] + */ + function inorderTraversal2($root) + { + $stack = new SplStack(); + while ($root || !$stack->isEmpty()) { + while ($root) { + $stack->push($root); + $root = $root->left; + } + $root = $stack->top(); + $stack->pop(); + $this->ret[] = $root->val; + $root = $root->right; + } + return $this->ret; + } + + /** + * 三、莫里斯遍历 有空再研究吧 + */ + + +} \ No newline at end of file From 0b0fcfc1b5aa7929bdbb4c8f3ac68618f60118b2 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 3 Dec 2020 12:23:09 +0800 Subject: [PATCH 066/192] =?UTF-8?q?=E6=90=9C=E7=B4=A2=E6=8F=92=E5=85=A5?= =?UTF-8?q?=E4=BD=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week3/35.search-insert-position.php | 56 +++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Week3/35.search-insert-position.php diff --git a/Week3/35.search-insert-position.php b/Week3/35.search-insert-position.php new file mode 100644 index 00000000..1128a791 --- /dev/null +++ b/Week3/35.search-insert-position.php @@ -0,0 +1,56 @@ +searchRightBorder($nums, $target); + return $pos; + } + + function searchRightBorder($nums, $target) + { + $l = 0; + $r = count($nums) - 1; + $ans = count($nums); + while ($l <= $r) { + $mid = $l + (($r - $l) >> 1); + if ($target <= $nums[$mid]) { + $r = $mid - 1; + $ans = $mid; + } else { + $l = $mid + 1; + } + } + return $ans; + } +} + +/** + * + * 输入: [1,3,5,6], 5 + * 输出: 2 + * 输入: [1,3,5,6], 2 + * 输出: 1 + * 输入: [1,3,5,6], 7 + * 输出: 4 + * 输入: [1,3,5,6], 0 + * 输出: 0 + * + */ +$nums = [1, 3, 5, 6]; +$target = 7; +$s = new Solution(); +$ret = $s->searchInsert($nums, $target); +print_r($ret); \ No newline at end of file From c418010209f25c03803544465104b92e5f85f022 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 3 Dec 2020 13:03:36 +0800 Subject: [PATCH 067/192] =?UTF-8?q?=E4=BA=8C=E5=88=86=E6=9F=A5=E6=89=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week3/704.binary-search.php | 40 +++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Week3/704.binary-search.php diff --git a/Week3/704.binary-search.php b/Week3/704.binary-search.php new file mode 100644 index 00000000..256b46b2 --- /dev/null +++ b/Week3/704.binary-search.php @@ -0,0 +1,40 @@ +> 1); + if ($nums[$mid] == $target) { + return $mid; + } elseif ($nums[$mid] < $target) { + $l = $mid + 1; + } else { + $r = $mid - 1; + } + } + return $ans; + } +} + +/** + *输入: nums = [-1,0,3,5,9,12], target = 9 + * 输出: 4 + */ + +$nums = [-1, 0, 3, 5, 9, 12]; +$target = 9; +$s = new Solution(); +$ret = $s->search($nums, $target); +print_r($ret); \ No newline at end of file From f5eb4772c2fadda53d3da75c86b02fff6c3bd397 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 3 Dec 2020 15:50:18 +0800 Subject: [PATCH 068/192] =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84?= =?UTF-8?q?=E5=89=8D=E5=BA=8F=E9=81=8D=E5=8E=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week2/144.binary-tree-preorder-traversal.php | 62 ++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Week2/144.binary-tree-preorder-traversal.php diff --git a/Week2/144.binary-tree-preorder-traversal.php b/Week2/144.binary-tree-preorder-traversal.php new file mode 100644 index 00000000..fa1c025a --- /dev/null +++ b/Week2/144.binary-tree-preorder-traversal.php @@ -0,0 +1,62 @@ +val = $val; + * $this->left = $left; + * $this->right = $right; + * } + * } + */ +class Solution +{ + + public $ret = []; + + /** + * 一、递归 O(N) O(N) + * 空间复杂度 平均为O(LogN) 最坏的情况下为链状O(N) + * @param TreeNode $root + * @return Integer[] + */ + function preorderTraversal($root) + { + $this->dfs($root); + return $this->ret; + } + + function dfs($root) + { + if (!$root) return; + $this->ret[] = $root->val; + $this->preorderTraversal($root->left); + $this->preorderTraversal($root->right); + } + + /** + * 二、栈 O(N) O(N) + * 空间复杂度 平均为O(LogN) 最坏的情况下为链状O(N) + * @param TreeNode $root + * @return Integer[] + */ + function preorderTraversal2($root) + { + $ret = []; + $stack = new SplStack(); + $stack->push($root); + while (!$stack->isEmpty()) { + $node = $stack->pop(); + if (!$node) continue; + $ret[] = $node->val; + $stack->push($node->right); + $stack->push($node->left); + } + return $ret; + } + +} \ No newline at end of file From 008dffde0d51dd465d8cb5125186549d0e51d9f5 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 3 Dec 2020 16:06:34 +0800 Subject: [PATCH 069/192] =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84?= =?UTF-8?q?=E5=90=8E=E7=BB=AD=E9=81=8D=E5=8E=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week2/145.binary-tree-postorder-traversal.php | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Week2/145.binary-tree-postorder-traversal.php diff --git a/Week2/145.binary-tree-postorder-traversal.php b/Week2/145.binary-tree-postorder-traversal.php new file mode 100644 index 00000000..729ffa57 --- /dev/null +++ b/Week2/145.binary-tree-postorder-traversal.php @@ -0,0 +1,59 @@ +val = $val; + * $this->left = $left; + * $this->right = $right; + * } + * } + */ +class Solution +{ + + public $ret = []; + + /** + * 一、递归 O(N) O(N) + * @param TreeNode $root + * @return Integer[] + */ + function postorderTraversal($root) + { + $this->dfs($root); + return $this->ret; + } + + function dfs($root) + { + if (!$root) return; + $this->dfs($root->left); + $this->dfs($root->right); + $this->ret[] = $root->val; + } + + /** + * 一、栈 O(N) O(N) + * @param TreeNode $root + * @return Integer[] + */ + function postorderTraversal2($root) + { + $ret = []; + $stack = new SplStack(); + $stack->push($root); + while (!$stack->isEmpty()) { + $node = $stack->pop(); + if (!$node) continue; + $ret[] = $node->val; + $stack->push($node->left); + $stack->push($node->right); + } + return array_reverse($ret); + } +} \ No newline at end of file From 896056b8531ab4c65ddb563ebc56ba47ddc3554e Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 3 Dec 2020 16:36:33 +0800 Subject: [PATCH 070/192] =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84?= =?UTF-8?q?=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../102.binary-tree-level-order-traversal.php | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Week2/102.binary-tree-level-order-traversal.php diff --git a/Week2/102.binary-tree-level-order-traversal.php b/Week2/102.binary-tree-level-order-traversal.php new file mode 100644 index 00000000..ebf6f542 --- /dev/null +++ b/Week2/102.binary-tree-level-order-traversal.php @@ -0,0 +1,39 @@ +val = $value; } + * } + */ +class Solution +{ + + /** + * 借助队列实现层序遍历 O(N) O(N) + * @param TreeNode $root + * @return Integer[][] + */ + function levelOrder($root) + { + $ret = []; + if (!$root) return $ret; + $queue = new SplQueue(); + $queue->enqueue($root); + while (!$queue->isEmpty()) { + $size = $queue->count(); + $list = []; + for ($i = 0; $i < $size; $i++) { + $node = $queue->dequeue(); + $list[] = $node->val; + if ($node->left) $queue->enqueue($node->left); + if ($node->right) $queue->enqueue($node->right); + } + $ret[] = $list; + } + return $ret; + } +} \ No newline at end of file From 3bf47482460606510ead0ce2c12ebea330ce480d Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 3 Dec 2020 17:02:23 +0800 Subject: [PATCH 071/192] =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E5=B1=82?= =?UTF-8?q?=E5=BA=8F=E9=81=8D=E5=8E=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../429.n-ary-tree-level-order-traversal.php | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Week2/429.n-ary-tree-level-order-traversal.php diff --git a/Week2/429.n-ary-tree-level-order-traversal.php b/Week2/429.n-ary-tree-level-order-traversal.php new file mode 100644 index 00000000..84697731 --- /dev/null +++ b/Week2/429.n-ary-tree-level-order-traversal.php @@ -0,0 +1,40 @@ +val = $val; + * $this->children = array(); + * } + * } + */ + +class Solution +{ + /** + * @param Node $root + * @return integer[][] + */ + function levelOrder($root) + { + $ret = []; + if (!$root) return $ret; + $queue = new SplQueue(); + $queue->enqueue($root); + while (!$queue->isEmpty()) { + $size = $queue->count(); + $list = []; + for ($i = 0; $i < $size; $i++) { + $node = $queue->dequeue(); + $list[] = $node->val; + foreach ($node->children as $child) { + if ($child) $queue->enqueue($child); + } + } + $ret[] = $list; + } + return $ret; + } +} \ No newline at end of file From 9b35406d8c08e077a9e9bfb4da4e670cb47e64d0 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 3 Dec 2020 17:18:16 +0800 Subject: [PATCH 072/192] =?UTF-8?q?N=E5=8F=89=E6=A0=91=E5=89=8D=E5=BA=8F?= =?UTF-8?q?=E9=81=8D=E5=8E=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week2/589.n-ary-tree-preorder-traversal.php | 57 +++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Week2/589.n-ary-tree-preorder-traversal.php diff --git a/Week2/589.n-ary-tree-preorder-traversal.php b/Week2/589.n-ary-tree-preorder-traversal.php new file mode 100644 index 00000000..d2924250 --- /dev/null +++ b/Week2/589.n-ary-tree-preorder-traversal.php @@ -0,0 +1,57 @@ +val = $val; + * $this->children = array(); + * } + * } + */ + +class Solution +{ + /** + * @param Node $root + * @return integer[] + */ + function preorder1($root) + { + $stack = $list = []; + array_push($stack, $root); + while ($stack) { + $node = array_pop($stack); + array_push($list, $node->val); + if ($node->children) { + foreach (array_reverse($node->children) as $child) { + array_push($stack, $child); + } + } + } + return $list; + } + + /** + * @param Node $root + * @return integer[] + */ + function preorder($root) + { + $ret = []; + if (!$root) return $ret; + $stack = new SplStack(); + $stack->push($root); + while (!$stack->isEmpty()) { + $node = $stack->pop(); + if (!$node) continue; + $ret[] = $node->val; + foreach (array_reverse($node->children) as $child) { + $stack->push($child); + } + } + return $ret; + } +} + From 7734f5eae1965ceae577eda4b142edb47abb059b Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 3 Dec 2020 17:46:57 +0800 Subject: [PATCH 073/192] =?UTF-8?q?N=E5=8F=89=E6=A0=91=E7=9A=84=E5=90=8E?= =?UTF-8?q?=E7=BB=AD=E9=81=8D=E5=8E=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week2/590.n-ary-tree-postorder-traversal.php | 59 ++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Week2/590.n-ary-tree-postorder-traversal.php diff --git a/Week2/590.n-ary-tree-postorder-traversal.php b/Week2/590.n-ary-tree-postorder-traversal.php new file mode 100644 index 00000000..3f35b461 --- /dev/null +++ b/Week2/590.n-ary-tree-postorder-traversal.php @@ -0,0 +1,59 @@ +val = $val; + * $this->children = array(); + * } + * } + */ + +class Solution +{ + /** + * 一、栈 迭代 O(M) O(M) M为树的节点树 + * @param Node $root + * @return integer[] + */ + function postorder2($root) + { + $ret = []; + if (!$root) return $ret; + $stack = new SplStack(); + $stack->push($root); + while (!$stack->isEmpty()) { + $node = $stack->pop(); + if (!$node) continue; + $ret[] = $node->val; + foreach ($node->children as $child) { + if ($child) $stack->push($child); + } + } + return array_reverse($ret); //N叉树后续遍历这个地方反转 + } + + + /** + * 一、递归 O(M) O(M) M为树的节点树 + * @param Node $root + * @return integer[] + */ + function postorder($root) + { + if (!$root) return []; + $this->dfs($root); + return $this->ret; + } + + function dfs($root) + { + if (!$root) return; + foreach ($root->children as $child) { + $this->dfs($child); + } + $this->ret[] = $root->val; + } +} \ No newline at end of file From 54feb66d1fce29a812cce9b1f3e2171129ebbff4 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 3 Dec 2020 17:52:34 +0800 Subject: [PATCH 074/192] =?UTF-8?q?N=E5=8F=89=E6=A0=91=E5=89=8D=E5=BA=8F?= =?UTF-8?q?=E9=81=8D=E5=8E=86=20=E5=A2=9E=E5=8A=A0=E9=80=92=E5=BD=92?= =?UTF-8?q?=E5=86=99=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week2/589.n-ary-tree-preorder-traversal.php | 26 +++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/Week2/589.n-ary-tree-preorder-traversal.php b/Week2/589.n-ary-tree-preorder-traversal.php index d2924250..8c9d6a73 100644 --- a/Week2/589.n-ary-tree-preorder-traversal.php +++ b/Week2/589.n-ary-tree-preorder-traversal.php @@ -34,10 +34,11 @@ function preorder1($root) } /** + * 一、栈迭代 O(M) O(M) * @param Node $root * @return integer[] */ - function preorder($root) + function preorder2($root) { $ret = []; if (!$root) return $ret; @@ -47,11 +48,32 @@ function preorder($root) $node = $stack->pop(); if (!$node) continue; $ret[] = $node->val; - foreach (array_reverse($node->children) as $child) { + foreach (array_reverse($node->children) as $child) { //N叉树前序遍历这个地方反转 $stack->push($child); } } return $ret; } + + /** + * 一、递归 O(M) O(M) + * @param Node $root + * @return integer[] + */ + function preorder($root) + { + if (!$root) return []; + $this->dfs($root); + return $this->ret; + } + + function dfs($root) + { + if (!$root) return; + $this->ret[] = $root->val; + foreach ($root->children as $child) { + $this->dfs($child); + } + } } From 40e65941b7f8c90bf2505948e3e80f4438cc6e30 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 3 Dec 2020 18:04:49 +0800 Subject: [PATCH 075/192] =?UTF-8?q?N=E5=8F=89=E6=A0=91=E7=9A=84=E6=9C=80?= =?UTF-8?q?=E5=A4=A7=E9=AB=98=E5=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week2/559.maximum-depth-of-n-ary-tree.php | 30 +++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Week2/559.maximum-depth-of-n-ary-tree.php diff --git a/Week2/559.maximum-depth-of-n-ary-tree.php b/Week2/559.maximum-depth-of-n-ary-tree.php new file mode 100644 index 00000000..e70b2177 --- /dev/null +++ b/Week2/559.maximum-depth-of-n-ary-tree.php @@ -0,0 +1,30 @@ +val = $val; + * $this->children = array(); + * } + * } + */ + +class Solution +{ + /** + * O(M) O(M) + * @param Node $root + * @return integer + */ + function maxDepth($root) + { + if (!$root) return 0; + $depth = 0; + foreach ($root->children as $child) { + $depth = max($depth, $this->maxDepth($child)); + } + return $depth + 1; + } +} \ No newline at end of file From dc83f5c2fc1c5e68f4fd7a851725024dfb4a2d5d Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 3 Dec 2020 19:07:08 +0800 Subject: [PATCH 076/192] =?UTF-8?q?=E4=B8=91=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week2/264.ugly-number-ii.php | 62 ++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Week2/264.ugly-number-ii.php diff --git a/Week2/264.ugly-number-ii.php b/Week2/264.ugly-number-ii.php new file mode 100644 index 00000000..b6b74c43 --- /dev/null +++ b/Week2/264.ugly-number-ii.php @@ -0,0 +1,62 @@ +preCalcUgly($n); + return $ret[$n - 1]; + } + + function preCalcUgly($n) + { + $primes = [2, 3, 5]; + $heap = new SplMinHeap(); + $this->hash = [1]; + $heap->insert(1); + for ($i = 0; $i < 1690; $i++) { + if (!$heap->isEmpty()) { + $v1 = $heap->top(); + $this->nums[] = $v1; + $heap->extract(); + for ($j = 0; $j < count($primes); $j++) { + $v2 = $v1 * $primes[$j]; + if (!in_array($v2, $this->hash)) { + $heap->insert($v2); + $this->hash[] = $v2; + } + } + } + } + return $this->nums; + } + + /** + * 二、使用动态规划(三指针)进行预计算 O(1)进行取值 + * @param Integer $n + * @return Integer + */ + function nthUglyNumber2($n) + { + $dp = [1]; + $p2 = $p3 = $p5 = 0; + for ($i = 0; $i < 1690; $i++) { + $min = min($dp[$p2] * 2, $dp[$p3] * 3, $dp[$p5] * 5); + $dp[] = $min; + if ($min == $dp[$p2] * 2) $p2++; + if ($min == $dp[$p3] * 3) $p3++; + if ($min == $dp[$p5] * 5) $p5++; + } + return $dp[$n - 1]; + } +} + +$s = new Solution(); +$ret = $s->nthUglyNumber2(5); +print_r($ret); \ No newline at end of file From 53c0465c8a396393095ad1fa8f8dd42b8dc44a48 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 3 Dec 2020 23:49:50 +0800 Subject: [PATCH 077/192] =?UTF-8?q?=E5=B2=9B=E5=B1=BF=E6=95=B0=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week2/200.number-of-islands.php | 109 ++++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 Week2/200.number-of-islands.php diff --git a/Week2/200.number-of-islands.php b/Week2/200.number-of-islands.php new file mode 100644 index 00000000..1bfd1228 --- /dev/null +++ b/Week2/200.number-of-islands.php @@ -0,0 +1,109 @@ +dfs($grid, $i, $j); + $num++; + } + } + } + return $num; + } + + function dfs(&$grid, $r, $c) + { + //print_r('r:' . $r . '|c:' . $c . PHP_EOL); + //print_r($grid); + if (!$this->inArea($grid, $r, $c)) return; //出界返回 + if ($grid[$r][$c] != 1) return; //非岛屿返回 + $grid[$r][$c] = 2; //标记感染 + $this->dfs($grid, $r - 1, $c); //向上遍历 + $this->dfs($grid, $r + 1, $c); //向下遍历 + $this->dfs($grid, $r, $c - 1); //向左遍历 + $this->dfs($grid, $r, $c + 1); //向右遍历 + } + + function inArea($grid, $r, $c) + { + return $r >= 0 && $r < count($grid) && $c >= 0 && $c < count($grid[0]); + } + + /** + * BFS 广度优先搜索 + 感染 + * @param String[][] $grid + * @return Integer + */ + function numIslands2($grid) + { + $r = count($grid); + $c = count($grid[0]); + $this->visited = []; + for ($i = 0; $i < $r; $i++) { + for ($j = 0; $j < $c; $j++) { + $this->visited[$i][$j] = 0; + } + } + $this->direction = [[-1, 0], [0, -1], [0, 1], [1, 0]]; + $num = 0; + for ($i = 0; $i < $r; $i++) { + for ($j = 0; $j < $c; $j++) { + if ($grid[$i][$j] == 1 && !$this->visited[$i][$j]) { + $this->bfs($grid, $i, $j, $c); + $num++; + } + } + } + return $num; + } + + function bfs($grid, $r, $c, $base) + { + $queue = new SplQueue(); + $code = $r * $base + $c; + $queue->enqueue($code); + $this->visited[$r][$c] = 1; + while (!$queue->isEmpty()) { + $code = $queue->dequeue(); + $x = floor($code / $base); + $y = $code % $base; + for ($i = 0; $i < count($this->direction); $i++) { + $newX = $x + $this->direction[$i][0]; + $newY = $y + $this->direction[$i][1]; + if ($this->inArea($grid, $newX, $newY) && $grid[$newX][$newY] && !$this->visited[$newX][$newY]) { + $queue->enqueue($newX * $base + $newY); + $this->visited[$newX][$newY] = 1; + } + } + } + } + +} + +$grid = [ + ["1", "1", "0"], + ["1", "1", "0"], + ["0", "0", "1"], +]; +$grid = [ + ["1", "1", "0", "0", "0"], + ["1", "1", "0", "0", "0"], + ["0", "0", "1", "0", "0"], + ["0", "0", "0", "1", "1"] +]; +$s = new Solution(); +$ret = $s->numIslands2($grid); +print_r($ret); \ No newline at end of file From c36095a85d9cc44ce1880a7484feeaa541112810 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Fri, 4 Dec 2020 10:20:57 +0800 Subject: [PATCH 078/192] =?UTF-8?q?=E5=B2=9B=E5=B1=BF=E7=9A=84=E5=91=A8?= =?UTF-8?q?=E9=95=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week2/463.island-perimeter.php | 77 ++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 Week2/463.island-perimeter.php diff --git a/Week2/463.island-perimeter.php b/Week2/463.island-perimeter.php new file mode 100644 index 00000000..ab810d04 --- /dev/null +++ b/Week2/463.island-perimeter.php @@ -0,0 +1,77 @@ +dfs($grid, $i, $j); + } + } + } + return $num; + } + + function dfs(&$grid, $r, $c) + { + if (!$this->inArea($grid, $r, $c)) return 1; //边界 + if ($grid[$r][$c] == 0) return 1; //海洋 + if ($grid[$r][$c] == 2) return 0; //已扫描 + $grid[$r][$c] = 2; + return + $this->dfs($grid, $r - 1, $c) + + $this->dfs($grid, $r + 1, $c) + + $this->dfs($grid, $r, $c - 1) + + $this->dfs($grid, $r, $c + 1); + } + + function inArea($grid, $r, $c) + { + return $r >= 0 && $r < count($grid) && $c >= 0 && $c < count($grid[0]); + } + + /** + * 迭代 O(MN) O(1) + * @param Integer[][] $grid + * @return Integer + */ + function islandPerimeter2($grid) + { + $dx = [-1, 0, 0, 1]; + $dy = [0, 1, -1, 0]; + $nr = count($grid); + $nc = count($grid[0]); + $num = 0; + for ($i = 0; $i < $nr; $i++) { + for ($j = 0; $j < $nc; $j++) { + if ($grid[$i][$j] == 1) { + for ($k = 0; $k < 4; $k++) { + $x = $i + $dx[$k]; + $y = $j + $dy[$k]; + if ($x < 0 || $y < 0 || $x >= $nr || $y >= $nc || $grid[$x][$y] == 0) { //边缘或海洋 + $num++; + } + } + } + } + } + return $num; + } + +} + +$grid = [[0, 1, 0, 0], [1, 1, 1, 0], [0, 1, 0, 0], [1, 1, 0, 0]]; +$s = new Solution(); +$ret = $s->islandPerimeter2($grid); +print_r($ret); \ No newline at end of file From 8f86fca5570a86ab8b0fd3abb857c6cd2579d6d0 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Fri, 4 Dec 2020 10:48:49 +0800 Subject: [PATCH 079/192] =?UTF-8?q?=E5=B2=9B=E5=B1=BF=E7=9A=84=E6=9C=80?= =?UTF-8?q?=E5=A4=A7=E9=9D=A2=E7=A7=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week2/695.max-area-of-island.php | 55 ++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Week2/695.max-area-of-island.php diff --git a/Week2/695.max-area-of-island.php b/Week2/695.max-area-of-island.php new file mode 100644 index 00000000..187d1c44 --- /dev/null +++ b/Week2/695.max-area-of-island.php @@ -0,0 +1,55 @@ +dfs($grid, $i, $j)); + } + } + } + return $maxArea; + } + + function dfs(&$grid, $r, $c) + { + if (!$this->inArea($grid, $r, $c)) return 0; + if ($grid[$r][$c] != 1) return 0; + $grid[$r][$c] = 2; + return 1 + + $this->dfs($grid, $r - 1, $c) + + $this->dfs($grid, $r + 1, $c) + + $this->dfs($grid, $r, $c - 1) + + $this->dfs($grid, $r, $c + 1); + } + + function inArea($grid, $r, $c) + { + return $r >= 0 && $r < count($grid) && $c >= 0 && $c < count($grid[0]); + } +} + +$grid = [[0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0], + [0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0]]; + +$s = new Solution(); +$ret = $s->maxAreaOfIsland($grid); +print_r($ret); + From bbb3ccdbc007ea34014d87f7cd0e78c388381471 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Fri, 4 Dec 2020 12:22:39 +0800 Subject: [PATCH 080/192] =?UTF-8?q?=E6=9C=80=E5=A4=A7=E4=BA=BA=E5=B7=A5?= =?UTF-8?q?=E5=B2=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week2/827.making-a-large-island.php | 111 ++++++++++++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 Week2/827.making-a-large-island.php diff --git a/Week2/827.making-a-large-island.php b/Week2/827.making-a-large-island.php new file mode 100644 index 00000000..514e3b46 --- /dev/null +++ b/Week2/827.making-a-large-island.php @@ -0,0 +1,111 @@ +bfs($grid, $i, $j, $nc, $color); + $areaMap[$color] = $this->dfs($grid, $i, $j, $color); + $color++; + } + } + } + //如果全是陆地 + if (max($areaMap) == $nr * $nc) { + return $nr * $nc; + } + //遍历所有海洋 将其填充成陆地 再 加上周围其他陆地的面积 求出最大的一个 + $maxArea = 1; + $dr = [[-1, 0], [0, -1], [1, 0], [0, 1]]; + for ($i = 0; $i < $nr; $i++) { + for ($j = 0; $j < $nc; $j++) { + $colorMap = []; + $area = 1; + if ($grid[$i][$j] == 0) { + for ($k = 0; $k < count($dr); $k++) { + $nx = $i + $dr[$k][0]; + $ny = $j + $dr[$k][1]; + if ($this->inArea($grid, $nx, $ny) && $grid[$nx][$ny] > 0 && !in_array($grid[$nx][$ny], $colorMap)) { + $colorMap[] = $grid[$nx][$ny]; + $area += $areaMap[$grid[$nx][$ny]]; + } + } + $maxArea = max($maxArea, $area); + } + } + } + return $maxArea; + } + + /** + * 深度优先搜索 染色 + 计算面积 + * @param $grid + * @param $r + * @param $c + * @param $color + */ + function dfs(&$grid, $r, $c, $color) + { + if (!$this->inArea($grid, $r, $c)) return 0; + if ($grid[$r][$c] == 0) return 0; + $grid[$r][$c] = $color; + return 1 + + $this->dfs($grid, $r + 1, $c, $color) + + $this->dfs($grid, $r - 1, $c, $color) + + $this->dfs($grid, $r, $c + 1, $color) + + $this->dfs($grid, $r, $c - 1, $color); + } + + /** + * 广度优先搜索 染色 + 计算面积 + * @param $grid + * @param $r + * @param $c + * @param $color + */ + function bfs(&$grid, $r, $c, $base, $color) + { + $dr = [[-1, 0], [0, -1], [1, 0], [0, 1]]; + $queue = new SplQueue(); + $queue->enqueue($r * $base + $c); + $grid[$r][$c] = $color; + $area = 1; + while (!$queue->isEmpty()) { + $code = $queue->dequeue(); + $x = floor($code / $base); + $y = $code % $base; + for ($k = 0; $k < count($dr); $k++) { + $nx = $x + $dr[$k][0]; + $ny = $y + $dr[$k][1]; + if ($this->inArea($grid, $nx, $ny) && $grid[$nx][$ny] == 1) { + $queue->enqueue($nx * $base + $ny); + $grid[$nx][$ny] = $color; + $area++; + } + } + } + return $area; + } + + function inArea($grid, $r, $c) + { + return $r >= 0 && $r < count($grid) && $c >= 0 && $c < count($grid[0]); + } +} + +$grid = [[1, 0], [0, 1]]; +$s = new Solution(); +$ret = $s->largestIsland($grid); +print_r($ret); \ No newline at end of file From e036b2248e07e89d9482b4da497371f7184628bc Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Fri, 4 Dec 2020 21:56:53 +0800 Subject: [PATCH 081/192] =?UTF-8?q?=E8=AF=BE=E7=A8=8B=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week2/207.course-schedule.php | 91 +++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 Week2/207.course-schedule.php diff --git a/Week2/207.course-schedule.php b/Week2/207.course-schedule.php new file mode 100644 index 00000000..567b453e --- /dev/null +++ b/Week2/207.course-schedule.php @@ -0,0 +1,91 @@ +enqueue($j); //所有入度为0课程入队 + } + } + $visited = 0; //记录已出队课程数 如果最后与numCourses相等 则说明可以完成 + while (!$queue->isEmpty()) { + $u = $queue->dequeue(); + $visited++; + foreach ($edgeMap[$u] as $v) { //遍历出队的课程影响到其他入度的课程 + if (--$inDegree[$v] == 0) { + $queue->enqueue($v); + } + } + } + return $visited == $numCourses; + } + + /** + * 二、以出度为切入点深度优先搜索DFS O(E + V) O(E + V) + * @param Integer $numCourses + * @param Integer[][] $prerequisites + * @return Boolean + */ + function canFinish2($numCourses, $prerequisites) + { + //构建 节点状态表 与 邻接关系表 + $this->valid = true; //无环 有解 + $visited = array_fill(0, $numCourses, 0); + $edgeMap = array_fill(0, $numCourses, []); + for ($i = 0; $i < count($prerequisites); $i++) { + $v = $prerequisites[$i][0]; //才能学 + $k = $prerequisites[$i][1]; //先学 + $edgeMap[$k][] = $v; + } + + for ($j = 0; $j < $numCourses; $j++) { + if ($visited[$j] == 0) { + $this->dfs($edgeMap, $visited, $j); + } + } + + return $this->valid; + } + + function dfs($edgeMap, &$visited, $u) + { + $visited[$u] = 1; + foreach ($edgeMap[$u] as $v) { + if ($visited[$v] == 0) { + $this->dfs($edgeMap, $visited, $v); + if (!$this->valid) return; + } elseif ($visited[$v] == 1) { + $this->valid = false; //有环 无解 + return; + } + } + $visited[$u] = 2; + } +} + +$numCourses = 6; +$prerequisites = [[3, 0], [3, 1], [4, 1], [4, 2], [5, 3], [5, 4]]; +$s = new Solution(); +$ret = $s->canFinish2($numCourses, $prerequisites); +var_dump($ret); \ No newline at end of file From f578b3caa47395b755e54d0153811265c4c63010 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Fri, 4 Dec 2020 22:23:32 +0800 Subject: [PATCH 082/192] =?UTF-8?q?=E6=9B=BF=E6=8D=A2=E7=A9=BA=E6=A0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week3/offer05.ti-huan-kong-ge-lcof.php | 28 ++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Week3/offer05.ti-huan-kong-ge-lcof.php diff --git a/Week3/offer05.ti-huan-kong-ge-lcof.php b/Week3/offer05.ti-huan-kong-ge-lcof.php new file mode 100644 index 00000000..b8929309 --- /dev/null +++ b/Week3/offer05.ti-huan-kong-ge-lcof.php @@ -0,0 +1,28 @@ +replaceSpace($str); +print_r($ret); \ No newline at end of file From 579f5fd8d8e7f8bf486bcbe538a178c14268893e Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sat, 5 Dec 2020 13:59:44 +0800 Subject: [PATCH 083/192] =?UTF-8?q?=E8=AF=BE=E7=A8=8B=E8=A1=A8II?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week2/210.course-schedule-ii.php | 100 +++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 Week2/210.course-schedule-ii.php diff --git a/Week2/210.course-schedule-ii.php b/Week2/210.course-schedule-ii.php new file mode 100644 index 00000000..4e976463 --- /dev/null +++ b/Week2/210.course-schedule-ii.php @@ -0,0 +1,100 @@ +enqueue($j); + } + } + + $num = 0; + while (!$queue->isEmpty()) { + $u = $queue->dequeue(); + $ret[] = $u; + $num++; + foreach ($edges[$u] as $v) { + if (--$inDegree[$v] == 0) { + $queue->enqueue($v); + } + } + } + return $num == $numCourses ? $ret : []; + } + + /** + * 一、DFS + * @param Integer $numCourses + * @param Integer[][] $prerequisites + * @return Integer[] + */ + function findOrder2($numCourses, $prerequisites) + { + $visited = array_fill(0, $numCourses, 0); + $edges = array_fill(0, $numCourses, []); // 这个地方容易出错 + for ($i = 0; $i < count($prerequisites); $i++) { + $v = $prerequisites[$i][0]; + $k = $prerequisites[$i][1]; + $edges[$k][] = $v; + } + + $this->ret = []; + $this->circle = false; + for ($j = 0; $j < $numCourses; $j++) { + if ($visited[$j] == 0) { //这个地方容易忘 + $this->dfs($edges, $visited, $j); + } + } + return $this->circle ? [] : array_reverse($this->ret); + } + + function dfs($edges, &$visited, $u) + { + $visited[$u] = 1; + foreach ($edges[$u] as $v) { + if ($visited[$v] == 0) { + $this->dfs($edges, $visited, $v); + if ($this->circle) return; + } elseif ($visited[$v] == 1) { + $this->circle = true; + return; + } + } + $visited[$u] = 2; + $this->ret[] = $u; + } +} + +/** + *输出: [0,1,2,3] or [0,2,1,3] + * 解释:总共有 4 门课程。要学习课程 3,你应该先完成课程 1 和课程 2。并且课程 1 和课程 2 都应该排在课程 0 之后。 + * 因此,一个正确的课程顺序是[0,1,2,3] 。另一个正确的排序是[0,2,1,3] 。 + */ +$prerequistes = [[1, 0], [1, 2], [0, 1]]; +$numCourses = 3; +$numCourses = 4; +$prerequistes = [[1, 0], [2, 0], [3, 1], [3, 2]]; + +$s = new Solution(); +$ret = $s->findOrder2($numCourses, $prerequistes); +print_r($ret); From 1e4827c3f43d537030b01dd274d289569244f5ac Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sat, 5 Dec 2020 22:48:55 +0800 Subject: [PATCH 084/192] =?UTF-8?q?=E4=BB=8E=E5=B0=BE=E5=88=B0=E5=A4=B4?= =?UTF-8?q?=E6=89=93=E5=8D=B0=E9=93=BE=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...cong-wei-dao-tou-da-yin-lian-biao-lcof.php | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Week3/offer06.cong-wei-dao-tou-da-yin-lian-biao-lcof.php diff --git a/Week3/offer06.cong-wei-dao-tou-da-yin-lian-biao-lcof.php b/Week3/offer06.cong-wei-dao-tou-da-yin-lian-biao-lcof.php new file mode 100644 index 00000000..f714135f --- /dev/null +++ b/Week3/offer06.cong-wei-dao-tou-da-yin-lian-biao-lcof.php @@ -0,0 +1,52 @@ +val = $val; } + * } + */ +class Solution +{ + + /** + * 一、栈 O(N) O(N) + * @param ListNode $head + * @return Integer[] + */ + function reversePrint2($head) + { + $ret = []; + $stack = new SplStack(); + while ($head) { + $stack->push($head->val); + $head = $head->next; + } + while (!$stack->isEmpty()) { + $ret[] = $stack->pop(); + } + return $ret; + } + + + /** + * 二、利用回溯 O(N) O(N) + * @param ListNode $head + * @return Integer[] + */ + function reversePrint($head) + { + $this->ret = []; + $this->dfs($head); + return $this->ret; + } + + function dfs($head) + { + if (!$head) return; + $this->dfs($head->next); + $this->ret[] = $head->val; + } +} \ No newline at end of file From 3e45604301a3576dd4d1fa23a3c98913c4b83d31 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sun, 6 Dec 2020 00:12:41 +0800 Subject: [PATCH 085/192] =?UTF-8?q?=E4=BB=8E=E5=89=8D=E5=BA=8F=E9=81=8D?= =?UTF-8?q?=E5=8E=86=E5=92=8C=E4=B8=AD=E5=BA=8F=E9=81=8D=E5=8E=86=E6=9E=84?= =?UTF-8?q?=E5=BB=BA=E4=BA=8C=E5=8F=89=E6=A0=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...ee-from-preorder-and-inorder-traversal.php | 102 ++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 Week3/105.construct-binary-tree-from-preorder-and-inorder-traversal.php diff --git a/Week3/105.construct-binary-tree-from-preorder-and-inorder-traversal.php b/Week3/105.construct-binary-tree-from-preorder-and-inorder-traversal.php new file mode 100644 index 00000000..05bc89ef --- /dev/null +++ b/Week3/105.construct-binary-tree-from-preorder-and-inorder-traversal.php @@ -0,0 +1,102 @@ +val = $value; + } +} + +class Solution +{ + + /** + * 一、递归 O(N) O(N) + * 时间复杂度:O(n),其中 n 是树中的节点个数。 + * 空间复杂度:O(n),除去返回的答案需要的 O(n) 空间之外,我们还需要使用 O(n) 的空间存储哈希映射,以及 O(h)(其中 h 是树的高度)的空间表示递归时栈空间。这里 h < n,所以总空间复杂度为 O(n)。 + * @param Integer[] $preorder + * @param Integer[] $inorder + * @return TreeNode + */ + function buildTree2($preorder, $inorder) + { + $this->inOrderPos = array_flip($inorder); + return $this->treeBuild($preorder, 0, count($preorder) - 1, $inorder, 0, count($inorder) - 1); + } + + function treeBuild($preOrder, $preL, $preR, $inOrder, $inL, $inR) + { + //print_r('1.preL:' . $preL . '|preR:' . $preR . '|inL:' . $inL . '|inR:' . $inR . PHP_EOL); + if ($preL > $preR || $inL > $inR) return null; + $rootVal = $preOrder[$preL]; + //$pIndex = $inL; while ($rootVal != $inOrder[$pIndex]) $pIndex++; //这么写时间复杂度就会变O(N^2) + //print_r('2.preL:' . $preL . '|preR:' . $preR . '|inL:' . $inL . '|inR:' . $inR . '|pIndex:' . $pIndex . '|rootVal:' . $rootVal . PHP_EOL); + $pIndex = $this->inOrderPos[$rootVal]; + $root = new TreeNode($rootVal); + $root->left = $this->treeBuild($preOrder, $preL + 1, $pIndex - $inL + $preL, $inOrder, $inL, $pIndex - 1); + $root->right = $this->treeBuild($preOrder, $pIndex - $inL + $preL + 1, $preR, $inOrder, $pIndex + 1, $inR); + return $root; + } + + /** + * 二、栈 O(N) O(N) + * 这个解法还是没看懂 有空再研究 + * @param Integer[] $preorder + * @param Integer[] $inorder + * @return TreeNode + */ + function buildTree($preorder, $inorder) + { + $pre = 0; + $in = 0; + $stack = new SplStack(); + $tmp = []; + $root = new TreeNode($preorder[$pre]); + $curRoot = $root; + $stack->push($curRoot); + $tmp[] = $curRoot->val; + $pre++; + while ($pre < count($preorder)) { + if ($curRoot->val == $inorder[$in]) { + print_r('[1].pre:' . $pre . '|curRoot:' . $curRoot->val . '|in:' . $in . '|stack:' . implode(',', $tmp) . PHP_EOL); + while (!$stack->isEmpty() && $stack->top()->val == $inorder[$in]) { + $curRoot = $stack->top(); + $stack->pop(); + array_pop($tmp); + $in++; + } + print_r('[2].pre:' . $pre . '|curRoot:' . $curRoot->val . '|in:' . $in . '|stack:' . implode(',', $tmp) . PHP_EOL); + $curRoot->right = new TreeNode($preorder[$pre]); + $curRoot = $curRoot->right; + $stack->push($curRoot); + $tmp[] = $curRoot->val; + $pre++; + } else { + print_r('[3].pre:' . $pre . '|curRoot:' . $curRoot->val . '|in:' . $in . '|stack:' . implode(',', $tmp) . PHP_EOL); + $curRoot->left = new TreeNode($preorder[$pre]); + $curRoot = $curRoot->left; + $stack->push($curRoot); + $tmp[] = $curRoot->val; + $pre++; + } + } + return $root; + } + +} + +$pre = [2, 1]; +$in = [1, 2]; +$pre = [3, 9, 20, 15, 7]; +$in = [9, 3, 15, 20, 7]; +$s = new Solution(); +$ret = $s->buildTree($pre, $in); +print_r($ret); \ No newline at end of file From e594dcaad0763a4b49f61f33b4086fb3f3ecea12 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sun, 6 Dec 2020 16:29:31 +0800 Subject: [PATCH 086/192] add Lib DEBUG --- Lib/BinaryTree.php | 32 ++++++++++++++++++++++++++++++++ Lib/TreeNode.php | 16 ++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 Lib/BinaryTree.php create mode 100644 Lib/TreeNode.php diff --git a/Lib/BinaryTree.php b/Lib/BinaryTree.php new file mode 100644 index 00000000..708cf543 --- /dev/null +++ b/Lib/BinaryTree.php @@ -0,0 +1,32 @@ +createTree($arrTree, 0); + $this->val = $root->val; + $this->left = $root->left; + $this->right = $root->right; + } + + function createTree($arrTree, $i) + { + if ($i >= count($arrTree)) return null; + $root = new TreeNode($arrTree[$i]); + $left = 2 * $i + 1; + $right = 2 * $i + 2; + $root->left = $this->createTree($arrTree, $left); + $root->right = $this->createTree($arrTree, $right); + return $root; + } +} + +//$arrtree = [3,5,1,6,2,0,8,null,null,7,4]; +//$a = new binarytree($arrtree); +//print_r($a); diff --git a/Lib/TreeNode.php b/Lib/TreeNode.php new file mode 100644 index 00000000..8ccda1cd --- /dev/null +++ b/Lib/TreeNode.php @@ -0,0 +1,16 @@ +val = $value; + } +} From d9d0397a822ade623c43b4cb69e1775a42848fbf Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sun, 6 Dec 2020 19:20:42 +0800 Subject: [PATCH 087/192] optimize null node --- Lib/BinaryTree.php | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/Lib/BinaryTree.php b/Lib/BinaryTree.php index 708cf543..3dc5cf95 100644 --- a/Lib/BinaryTree.php +++ b/Lib/BinaryTree.php @@ -21,12 +21,18 @@ function createTree($arrTree, $i) $root = new TreeNode($arrTree[$i]); $left = 2 * $i + 1; $right = 2 * $i + 2; - $root->left = $this->createTree($arrTree, $left); - $root->right = $this->createTree($arrTree, $right); + $rootLeft = $this->createTree($arrTree, $left); + if (!is_null($rootLeft->val)) { + $root->left = $rootLeft; + } + $rootRight = $this->createTree($arrTree, $right); + if (!is_null($rootRight->val)) { + $root->right = $rootRight; + } return $root; } } -//$arrtree = [3,5,1,6,2,0,8,null,null,7,4]; -//$a = new binarytree($arrtree); +//$arrTree = [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4]; +//$a = new BinaryTree($arrTree); //print_r($a); From 72a090d0e46dfe31bff3ae91c79ccd64495c9e17 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sun, 6 Dec 2020 19:23:19 +0800 Subject: [PATCH 088/192] optimize notice --- Lib/BinaryTree.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Lib/BinaryTree.php b/Lib/BinaryTree.php index 3dc5cf95..927600db 100644 --- a/Lib/BinaryTree.php +++ b/Lib/BinaryTree.php @@ -22,11 +22,11 @@ function createTree($arrTree, $i) $left = 2 * $i + 1; $right = 2 * $i + 2; $rootLeft = $this->createTree($arrTree, $left); - if (!is_null($rootLeft->val)) { + if ($rootLeft && !is_null($rootLeft->val)) { $root->left = $rootLeft; } $rootRight = $this->createTree($arrTree, $right); - if (!is_null($rootRight->val)) { + if ($rootRight && !is_null($rootRight->val)) { $root->right = $rootRight; } return $root; From ba4e809895d5223fed1bdb787642f67e9bd22883 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sun, 6 Dec 2020 21:40:39 +0800 Subject: [PATCH 089/192] =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84?= =?UTF-8?q?=E6=9C=80=E8=BF=91=E5=85=AC=E5=85=B1=E7=A5=96=E5=85=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...owest-common-ancestor-of-a-binary-tree.php | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Week3/236.lowest-common-ancestor-of-a-binary-tree.php diff --git a/Week3/236.lowest-common-ancestor-of-a-binary-tree.php b/Week3/236.lowest-common-ancestor-of-a-binary-tree.php new file mode 100644 index 00000000..05c0cff6 --- /dev/null +++ b/Week3/236.lowest-common-ancestor-of-a-binary-tree.php @@ -0,0 +1,48 @@ +lowestCommonAncestor($root->left, $p, $q); + $right = $this->lowestCommonAncestor($root->right, $p, $q); + if (!$left) return $right; + if (!$right) return $left; + return $root; + } + + function dfs($root) + { + if (!$root) return; + print_r('1 => ' . $root->val . PHP_EOL); + $this->dfs($root->left); + print_r('2 => ' . $root->val . PHP_EOL); + $this->dfs($root->right); + print_r('3 => ' . $root->val . PHP_EOL); + } +} + +/** + * 输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 + * 输出: 3 + * 解释: 节点 5 和节点 1 的最近公共祖先是节点 3。 + */ + +$tree = [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4]; +$root = new BinaryTree($tree); +//print_r($root); +$s = new Solution(); +//$s->dfs($root); +$p = $root->left->right->right; +$q = $root->left->right->left; +$ret = $s->lowestCommonAncestor($root, $p, $q); +print_r($ret); From 099f54ba135cd90e79e96494e7635e38aaee073c Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Mon, 7 Dec 2020 10:49:17 +0800 Subject: [PATCH 090/192] =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E5=B1=82?= =?UTF-8?q?=E5=BA=8F=E9=81=8D=E5=8E=86=E5=A2=9E=E5=8A=A0=E9=80=92=E5=BD=92?= =?UTF-8?q?=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../102.binary-tree-level-order-traversal.php | 31 +++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/Week2/102.binary-tree-level-order-traversal.php b/Week2/102.binary-tree-level-order-traversal.php index ebf6f542..776cf7df 100644 --- a/Week2/102.binary-tree-level-order-traversal.php +++ b/Week2/102.binary-tree-level-order-traversal.php @@ -1,4 +1,5 @@ dfs($root, 0, $ret); + return $ret; + } + + function dfs($root, $level, &$ret) + { + if (!$root) return; + $ret[$level][] = $root->val; + $this->dfs($root->left, $level + 1, $ret); + $this->dfs($root->right, $level + 1, $ret); + } + +} + +$root = new BinaryTree([3, 9, 20, null, null, 15, 7]); +$s = new Solution(); +$ret = $s->levelOrder2($root); +print_r($ret); \ No newline at end of file From ecd46560ad74052748a6ce93fe4fbd67227d5c6e Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Mon, 7 Dec 2020 20:10:14 +0800 Subject: [PATCH 091/192] =?UTF-8?q?=E5=8D=95=E8=AF=8D=E6=8E=A5=E9=BE=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week4/127.word-ladder.php | 143 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 143 insertions(+) create mode 100644 Week4/127.word-ladder.php diff --git a/Week4/127.word-ladder.php b/Week4/127.word-ladder.php new file mode 100644 index 00000000..74ce0ac8 --- /dev/null +++ b/Week4/127.word-ladder.php @@ -0,0 +1,143 @@ +enqueue($beginWord); + $visited[] = $beginWord; + + $step = 1; + while (!$queue->isEmpty()) { + $size = $queue->count(); + for ($i = 0; $i < $size; $i++) { + $curWord = $queue->dequeue(); + for ($j = 0; $j < strlen($curWord); $j++) { + $oChar = $curWord[$j]; + for ($k = 'a'; $k <= 'z'; $k++) { + if ($oChar == $k) continue; + $nChar = $k; + $curWord[$j] = $nChar; + $nextWord = $curWord; + if (isset($list[$nextWord])) { + if ($nextWord == $endWord) { + return $step + 1; + } + if (!in_array($nextWord, $visited)) { + $queue->enqueue($nextWord); + $visited[] = $nextWord; + } + } + } + $curWord[$j] = $oChar; + } + } + $step++; + } + return 0; + } + + /** + * 一、单向广度优先搜索 + * 这个也挺慢的不过相比上一个快不少 能AC + * @param $beginWord + * @param $endWord + * @param $wordList + * @return int|mixed + */ + function ladderLength2($beginWord, $endWord, $wordList) + { + + if (!in_array($endWord, $wordList)) return 0; + // 数组中的键和值交换一下 + $newWordList = array_flip($wordList); + $queue = new SplQueue(); + $queue->enqueue([$beginWord, 1]); + while (!$queue->isEmpty()) { + list($word, $step) = $queue->dequeue(); + if ($word == $endWord) return $step; + for ($j = 0; $j < strlen($word); $j++) { + for ($k = 'a'; $k <= 'z'; $k++) { + $nextWord = $word; + $nextWord[$j] = $k; + if (isset($newWordList[$nextWord])) { + $queue->enqueue([$nextWord, $step + 1]); + unset($newWordList[$nextWord]); + } + } + } + } + return 0; + } + + /** + * 双向BFS + * 这个相当快 + * @param $beginWord + * @param $endWord + * @param $wordList + * @return int + */ + function ladderLength($beginWord, $endWord, $wordList) + { + if (!in_array($endWord, $wordList)) return 0; + // 数组中的键和值交换一下 + $newWordList = array_flip($wordList); + $s1[] = $beginWord; + $s2[] = $endWord; + $n = strlen($beginWord); + $step = 0; + while (!empty($s1)) { + $step++; + // 依次双向 BFS 实现,始终使用变量 s1 去运算 + if (count($s1) > count($s2)) { + $temp = $s1; + $s1 = $s2; + $s2 = $temp; + } + $s = []; + foreach ($s1 as $word) { + for ($i = 0; $i < $n; $i++) { + $nextWord = $word; + for ($ch = ord('a'); $ch <= ord('z'); $ch++) { + $nextWord[$i] = chr($ch); + if (in_array($nextWord, $s2)) return $step + 1; + if (isset($newWordList[$nextWord])) { + $s[] = $nextWord; + unset($newWordList[$nextWord]); + } + } + } + } + $s1 = $s; + } + return 0; + } +} + +$beginWord = 'a'; +$endWord = 'c'; +$wordList = ['a', 'b', 'c']; +$beginWord = 'hit'; +$endWord = 'cog'; +$wordList = ['hot', 'dot', 'dog', 'lot', 'log', 'cog']; +$beginWord = 'nanny'; +$endWord = 'aloud'; +$wordList = ["ricky", "grind", "cubic", "panic", "lover", "farce", "gofer", "sales", "flint", "omens", "lipid", "briny", "cloth", "anted", "slime", "oaten", "harsh", "touts", "stoop", "cabal", "lazed", "elton", "skunk", "nicer", "pesky", "kusch", "bused", "kinda", "tunis", "enjoy", "aches", "prowl", "babar", "rooms", "burst", "slush", "pines", "urine", "pinky", "bayed", "mania", "light", "flare", "wares", "women", "verne", "moron", "shine", "bluer", "zeros", "bleak", "brief", "tamra", "vasts", "jamie", "lairs", "penal", "worst", "yowls", "pills", "taros", "addle", "alyce", "creep", "saber", "floyd", "cures", "soggy", "vexed", "vilma", "cabby", "verde", "euler", "cling", "wanna", "jenny", "donor", "stole", "sakha", "blake", "sanes", "riffs", "forge", "horus", "sered", "piked", "prosy", "wases", "glove", "onset", "spake", "benin", "talks", "sites", "biers", "wendy", "dante", "allan", "haven", "nears", "shaka", "sloth", "perky", "spear", "spend", "clint", "dears", "sadly", "units", "vista", "hinds", "marat", "natal", "least", "bough", "pales", "boole", "ditch", "greys", "slunk", "bitch", "belts", "sense", "skits", "monty", "yawns", "music", "hails", "alien", "gibes", "lille", "spacy", "argot", "wasps", "drubs", "poops", "bella", "clone", "beast", "emend", "iring", "start", "darla", "bells", "cults", "dhaka", "sniff", "seers", "bantu", "pages", "fever", "tacky", "hoses", "strop", "climb", "pairs", "later", "grant", "raven", "stael", "drips", "lucid", "awing", "dines", "balms", "della", "galen", "toned", "snips", "shady", "chili", "fears", "nurse", "joint", "plump", "micky", "lions", "jamal", "queer", "ruins", "frats", "spoof", "semen", "pulps", "oldie", "coors", "rhone", "papal", "seals", "spans", "scaly", "sieve", "klaus", "drums", "tided", "needs", "rider", "lures", "treks", "hares", "liner", "hokey", "boots", "primp", "laval", "limes", "putts", "fonda", "damon", "pikes", "hobbs", "specs", "greet", "ketch", "braid", "purer", "tsars", "berne", "tarts", "clean", "grate", "trips", "chefs", "timex", "vicky", "pares", "price", "every", "beret", "vices", "jodie", "fanny", "mails", "built", "bossy", "farms", "pubic", "gongs", "magma", "quads", "shell", "jocks", "woods", "waded", "parka", "jells", "worse", "diner", "risks", "bliss", "bryan", "terse", "crier", "incur", "murky", "gamed", "edges", "keens", "bread", "raced", "vetch", "glint", "zions", "porno", "sizes", "mends", "ached", "allie", "bands", "plank", "forth", "fuels", "rhyme", "wimpy", "peels", "foggy", "wings", "frill", "edgar", "slave", "lotus", "point", "hints", "germs", "clung", "limed", "loafs", "realm", "myron", "loopy", "plush", "volts", "bimbo", "smash", "windy", "sours", "choke", "karin", "boast", "whirr", "tiber", "dimes", "basel", "cutes", "pinto", "troll", "thumb", "decor", "craft", "tared", "split", "josue", "tramp", "screw", "label", "lenny", "apses", "slept", "sikhs", "child", "bouts", "cites", "swipe", "lurks", "seeds", "fists", "hoard", "steed", "reams", "spoil", "diego", "peale", "bevel", "flags", "mazes", "quart", "snipe", "latch", "lards", "acted", "falls", "busby", "holed", "mummy", "wrong", "wipes", "carlo", "leers", "wails", "night", "pasty", "eater", "flunk", "vedas", "curse", "tyros", "mirth", "jacky", "butte", "wired", "fixes", "tares", "vague", "roved", "stove", "swoon", "scour", "coked", "marge", "cants", "comic", "corns", "zilch", "typos", "lives", "truer", "comma", "gaily", "teals", "witty", "hyper", "croat", "sways", "tills", "hones", "dowel", "llano", "clefs", "fores", "cinch", "brock", "vichy", "bleed", "nuder", "hoyle", "slams", "macro", "arabs", "tauts", "eager", "croak", "scoop", "crime", "lurch", "weals", "fates", "clipt", "teens", "bulls", "domed", "ghana", "culls", "frame", "hanky", "jared", "swain", "truss", "drank", "lobby", "lumps", "pansy", "whews", "saris", "trite", "weeps", "dozes", "jeans", "flood", "chimu", "foxes", "gelds", "sects", "scoff", "poses", "mares", "famed", "peers", "hells", "laked", "zests", "wring", "steal", "snoot", "yodel", "scamp", "ellis", "bandy", "marry", "jives", "vises", "blurb", "relay", "patch", "haley", "cubit", "heine", "place", "touch", "grain", "gerry", "badly", "hooke", "fuchs", "savor", "apron", "judge", "loren", "britt", "smith", "tammy", "altar", "duels", "huber", "baton", "dived", "apace", "sedan", "basts", "clark", "mired", "perch", "hulks", "jolly", "welts", "quack", "spore", "alums", "shave", "singe", "lanny", "dread", "profs", "skeet", "flout", "darin", "newed", "steer", "taine", "salvo", "mites", "rules", "crash", "thorn", "olive", "saves", "yawed", "pique", "salon", "ovens", "dusty", "janie", "elise", "carve", "winds", "abash", "cheep", "strap", "fared", "discs", "poxed", "hoots", "catch", "combo", "maize", "repay", "mario", "snuff", "delve", "cored", "bards", "sudan", "shuns", "yukon", "jowls", "wayne", "torus", "gales", "creek", "prove", "needy", "wisps", "terri", "ranks", "books", "dicky", "tapes", "aping", "padre", "roads", "nines", "seats", "flats", "rains", "moira", "basic", "loves", "pulls", "tough", "gills", "codes", "chest", "teeny", "jolts", "woody", "flame", "asked", "dulls", "hotly", "glare", "mucky", "spite", "flake", "vines", "lindy", "butts", "froth", "beeps", "sills", "bunny", "flied", "shaun", "mawed", "velds", "voled", "doily", "patel", "snake", "thigh", "adler", "calks", "desks", "janus", "spunk", "baled", "match", "strip", "hosed", "nippy", "wrest", "whams", "calfs", "sleet", "wives", "boars", "chain", "table", "duked", "riped", "edens", "galas", "huffs", "biddy", "claps", "aleut", "yucks", "bangs", "quids", "glenn", "evert", "drunk", "lusts", "senna", "slate", "manet", "roted", "sleep", "loxes", "fluky", "fence", "clamp", "doted", "broad", "sager", "spark", "belch", "mandy", "deana", "beyer", "hoist", "leafy", "levee", "libel", "tonic", "aloes", "steam", "skews", "tides", "stall", "rifts", "saxon", "mavis", "asama", "might", "dotes", "tangs", "wroth", "kited", "salad", "liens", "clink", "glows", "balky", "taffy", "sided", "sworn", "oasis", "tenth", "blurt", "tower", "often", "walsh", "sonny", "andes", "slump", "scans", "boded", "chive", "finer", "ponce", "prune", "sloes", "dined", "chums", "dingo", "harte", "ahead", "event", "freer", "heart", "fetch", "sated", "soapy", "skins", "royal", "cuter", "loire", "minot", "aisle", "horny", "slued", "panel", "eight", "snoop", "pries", "clive", "pored", "wrist", "piped", "daren", "cells", "parks", "slugs", "cubed", "highs", "booze", "weary", "stain", "hoped", "finny", "weeds", "fetid", "racer", "tasks", "right", "saint", "shahs", "basis", "refer", "chart", "seize", "lulls", "slant", "belay", "clots", "jinny", "tours", "modes", "gloat", "dunks", "flute", "conch", "marts", "aglow", "gayer", "lazes", "dicks", "chime", "bears", "sharp", "hatch", "forms", "terry", "gouda", "thins", "janet", "tonya", "axons", "sewed", "danny", "rowdy", "dolts", "hurry", "opine", "fifty", "noisy", "spiky", "humid", "verna", "poles", "jayne", "pecos", "hooky", "haney", "shams", "snots", "sally", "ruder", "tempe", "plunk", "shaft", "scows", "essie", "dated", "fleet", "spate", "bunin", "hikes", "sodas", "filly", "thyme", "fiefs", "perks", "chary", "kiths", "lidia", "lefty", "wolff", "withe", "three", "crawl", "wotan", "brown", "japed", "tolls", "taken", "threw", "crave", "clash", "layer", "tends", "notes", "fudge", "musky", "bawdy", "aline", "matts", "shirr", "balks", "stash", "wicks", "crepe", "foods", "fares", "rotes", "party", "petty", "press", "dolly", "mangy", "leeks", "silly", "leant", "nooks", "chapt", "loose", "caged", "wages", "grist", "alert", "sheri", "moody", "tamps", "hefts", "souls", "rubes", "rolex", "skulk", "veeps", "nonce", "state", "level", "whirl", "bight", "grits", "reset", "faked", "spiny", "mixes", "hunks", "major", "missy", "arius", "damns", "fitly", "caped", "mucus", "trace", "surat", "lloyd", "furry", "colin", "texts", "livia", "reply", "twill", "ships", "peons", "shear", "norms", "jumbo", "bring", "masks", "zippy", "brine", "dorks", "roded", "sinks", "river", "wolfs", "strew", "myths", "pulpy", "prank", "veins", "flues", "minus", "phone", "banns", "spell", "burro", "brags", "boyle", "lambs", "sides", "knees", "clews", "aired", "skirt", "heavy", "dimer", "bombs", "scums", "hayes", "chaps", "snugs", "dusky", "loxed", "ellen", "while", "swank", "track", "minim", "wiled", "hazed", "roofs", "cantu", "sorry", "roach", "loser", "brass", "stint", "jerks", "dirks", "emory", "campy", "poise", "sexed", "gamer", "catty", "comte", "bilbo", "fasts", "ledge", "drier", "idles", "doors", "waged", "rizal", "pured", "weirs", "crisp", "tasty", "sored", "palmy", "parts", "ethel", "unify", "crows", "crest", "udder", "delis", "punks", "dowse", "totes", "emile", "coded", "shops", "poppa", "pours", "gushy", "tiffs", "shads", "birds", "coils", "areas", "boons", "hulls", "alter", "lobes", "pleat", "depth", "fires", "pones", "serra", "sweat", "kline", "malay", "ruled", "calve", "tired", "drabs", "tubed", "wryer", "slung", "union", "sonya", "aided", "hewed", "dicey", "grids", "nixed", "whits", "mills", "buffs", "yucky", "drops", "ready", "yuppy", "tweet", "napes", "cadre", "teach", "rasps", "dowdy", "hoary", "canto", "posed", "dumbo", "kooks", "reese", "snaky", "binge", "byron", "phony", "safer", "friar", "novel", "scale", "huron", "adorn", "carla", "fauna", "myers", "hobby", "purse", "flesh", "smock", "along", "boils", "pails", "times", "panza", "lodge", "clubs", "colby", "great", "thing", "peaks", "diana", "vance", "whets", "bergs", "sling", "spade", "soaks", "beach", "traps", "aspen", "romps", "boxed", "fakir", "weave", "nerds", "swazi", "dotty", "curls", "diver", "jonas", "waite", "verbs", "yeast", "lapel", "barth", "soars", "hooks", "taxed", "slews", "gouge", "slags", "chang", "chafe", "saved", "josie", "syncs", "fonds", "anion", "actor", "seems", "pyrex", "isiah", "glued", "groin", "goren", "waxes", "tonia", "whine", "scads", "knelt", "teaks", "satan", "tromp", "spats", "merry", "wordy", "stake", "gland", "canal", "donna", "lends", "filed", "sacks", "shied", "moors", "paths", "older", "pooch", "balsa", "riced", "facet", "decaf", "attic", "elder", "akron", "chomp", "chump", "picky", "money", "sheer", "bolls", "crabs", "dorms", "water", "veers", "tease", "dummy", "dumbs", "lethe", "halls", "rifer", "demon", "fucks", "whips", "plops", "fuses", "focal", "taces", "snout", "edict", "flush", "burps", "dawes", "lorry", "spews", "sprat", "click", "deann", "sited", "aunts", "quips", "godly", "pupil", "nanny", "funks", "shoon", "aimed", "stacy", "helms", "mints", "banks", "pinch", "local", "twine", "pacts", "deers", "halos", "slink", "preys", "potty", "ruffs", "pusan", "suits", "finks", "slash", "prods", "dense", "edsel", "heeds", "palls", "slats", "snits", "mower", "rares", "ailed", "rouge", "ellie", "gated", "lyons", "duded", "links", "oaths", "letha", "kicks", "firms", "gravy", "month", "kongo", "mused", "ducal", "toted", "vocal", "disks", "spied", "studs", "macao", "erick", "coupe", "starr", "reaps", "decoy", "rayon", "nicks", "breed", "cosby", "haunt", "typed", "plain", "trays", "muled", "saith", "drano", "cower", "snows", "buses", "jewry", "argus", "doers", "flays", "swish", "resin", "boobs", "sicks", "spies", "bails", "wowed", "mabel", "check", "vapid", "bacon", "wilda", "ollie", "loony", "irked", "fraud", "doles", "facts", "lists", "gazed", "furls", "sunks", "stows", "wilde", "brick", "bowed", "guise", "suing", "gates", "niter", "heros", "hyped", "clomp", "never", "lolls", "rangy", "paddy", "chant", "casts", "terns", "tunas", "poker", "scary", "maims", "saran", "devon", "tripe", "lingo", "paler", "coped", "bride", "voted", "dodge", "gross", "curds", "sames", "those", "tithe", "steep", "flaks", "close", "swops", "stare", "notch", "prays", "roles", "crush", "feuds", "nudge", "baned", "brake", "plans", "weepy", "dazed", "jenna", "weiss", "tomes", "stews", "whist", "gibed", "death", "clank", "cover", "peeks", "quick", "abler", "daddy", "calls", "scald", "lilia", "flask", "cheer", "grabs", "megan", "canes", "jules", "blots", "mossy", "begun", "freak", "caved", "hello", "hades", "theed", "wards", "darcy", "malta", "peter", "whorl", "break", "downs", "odder", "hoofs", "kiddo", "macho", "fords", "liked", "flees", "swing", "elect", "hoods", "pluck", "brook", "astir", "bland", "sward", "modal", "flown", "ahmad", "waled", "craps", "cools", "roods", "hided", "plath", "kings", "grips", "gives", "gnats", "tabby", "gauls", "think", "bully", "fogey", "sawed", "lints", "pushy", "banes", "drake", "trail", "moral", "daley", "balds", "chugs", "geeky", "darts", "soddy", "haves", "opens", "rends", "buggy", "moles", "freud", "gored", "shock", "angus", "puree", "raves", "johns", "armed", "packs", "minis", "reich", "slots", "totem", "clown", "popes", "brute", "hedge", "latin", "stoke", "blend", "pease", "rubik", "greer", "hindi", "betsy", "flows", "funky", "kelli", "humps", "chewy", "welds", "scowl", "yells", "cough", "sasha", "sheaf", "jokes", "coast", "words", "irate", "hales", "camry", "spits", "burma", "rhine", "bends", "spill", "stubs", "power", "voles", "learn", "knoll", "style", "twila", "drove", "dacca", "sheen", "papas", "shale", "jones", "duped", "tunny", "mouse", "floss", "corks", "skims", "swaps", "inned", "boxer", "synch", "skies", "strep", "bucks", "belau", "lower", "flaky", "quill", "aural", "rufus", "floes", "pokes", "sends", "sates", "dally", "boyer", "hurts", "foyer", "gowns", "torch", "luria", "fangs", "moats", "heinz", "bolts", "filet", "firth", "begot", "argue", "youth", "chimp", "frogs", "kraft", "smite", "loges", "loons", "spine", "domes", "pokey", "timur", "noddy", "doggy", "wades", "lanes", "hence", "louts", "turks", "lurid", "goths", "moist", "bated", "giles", "stood", "winos", "shins", "potts", "brant", "vised", "alice", "rosie", "dents", "babes", "softy", "decay", "meats", "tanya", "rusks", "pasts", "karat", "nuked", "gorge", "kinks", "skull", "noyce", "aimee", "watch", "cleat", "stuck", "china", "testy", "doses", "safes", "stage", "bayes", "twins", "limps", "denis", "chars", "flaps", "paces", "abase", "grays", "deans", "maria", "asset", "smuts", "serbs", "whigs", "vases", "robyn", "girls", "pents", "alike", "nodal", "molly", "swigs", "swill", "slums", "rajah", "bleep", "beget", "thanh", "finns", "clock", "wafts", "wafer", "spicy", "sorer", "reach", "beats", "baker", "crown", "drugs", "daisy", "mocks", "scots", "fests", "newer", "agate", "drift", "marta", "chino", "flirt", "homed", "bribe", "scram", "bulks", "servo", "vesta", "divas", "preps", "naval", "tally", "shove", "ragas", "blown", "droll", "tryst", "lucky", "leech", "lines", "sires", "pyxed", "taper", "trump", "payee", "midge", "paris", "bored", "loads", "shuts", "lived", "swath", "snare", "boned", "scars", "aeons", "grime", "writs", "paige", "rungs", "blent", "signs", "davis", "dials", "daubs", "rainy", "fawns", "wrier", "golds", "wrath", "ducks", "allow", "hosea", "spike", "meals", "haber", "muses", "timed", "broom", "burks", "louis", "gangs", "pools", "vales", "altai", "elope", "plied", "slain", "chasm", "entry", "slide", "bawls", "title", "sings", "grief", "viola", "doyle", "peach", "davit", "bench", "devil", "latex", "miles", "pasha", "tokes", "coves", "wheel", "tried", "verdi", "wanda", "sivan", "prior", "fryer", "plots", "kicky", "porch", "shill", "coats", "borne", "brink", "pawed", "erwin", "tense", "stirs", "wends", "waxen", "carts", "smear", "rival", "scare", "phase", "bragg", "crane", "hocks", "conan", "bests", "dares", "molls", "roots", "dunes", "slips", "waked", "fours", "bolds", "slosh", "yemen", "poole", "solid", "ports", "fades", "legal", "cedes", "green", "curie", "seedy", "riper", "poled", "glade", "hosts", "tools", "razes", "tarry", "muddy", "shims", "sword", "thine", "lasts", "bloat", "soled", "tardy", "foots", "skiff", "volta", "murks", "croci", "gooks", "gamey", "pyxes", "poems", "kayla", "larva", "slaps", "abuse", "pings", "plows", "geese", "minks", "derby", "super", "inked", "manic", "leaks", "flops", "lajos", "fuzes", "swabs", "twigs", "gummy", "pyres", "shrew", "islet", "doled", "wooly", "lefts", "hunts", "toast", "faith", "macaw", "sonia", "leafs", "colas", "conks", "altos", "wiped", "scene", "boors", "patsy", "meany", "chung", "wakes", "clear", "ropes", "tahoe", "zones", "crate", "tombs", "nouns", "garth", "puked", "chats", "hanks", "baked", "binds", "fully", "soaps", "newel", "yarns", "puers", "carps", "spelt", "lully", "towed", "scabs", "prime", "blest", "patty", "silky", "abner", "temps", "lakes", "tests", "alias", "mines", "chips", "funds", "caret", "splat", "perry", "turds", "junks", "cramp", "saned", "peary", "snarl", "fired", "stung", "nancy", "bulge", "styli", "seams", "hived", "feast", "triad", "jaded", "elvin", "canny", "birth", "routs", "rimed", "pusey", "laces", "taste", "basie", "malls", "shout", "prier", "prone", "finis", "claus", "loops", "heron", "frump", "spare", "menus", "ariel", "crams", "bloom", "foxed", "moons", "mince", "mixed", "piers", "deres", "tempt", "dryer", "atone", "heats", "dario", "hawed", "swims", "sheet", "tasha", "dings", "clare", "aging", "daffy", "wried", "foals", "lunar", "havel", "irony", "ronny", "naves", "selma", "gurus", "crust", "percy", "murat", "mauro", "cowed", "clang", "biker", "harms", "barry", "thump", "crude", "ulnae", "thong", "pager", "oases", "mered", "locke", "merle", "soave", "petal", "poser", "store", "winch", "wedge", "inlet", "nerdy", "utter", "filth", "spray", "drape", "pukes", "ewers", "kinds", "dates", "meier", "tammi", "spoor", "curly", "chill", "loped", "gooey", "boles", "genet", "boost", "beets", "heath", "feeds", "growl", "livid", "midst", "rinds", "fresh", "waxed", "yearn", "keeps", "rimes", "naked", "flick", "plies", "deeps", "dirty", "hefty", "messy", "hairy", "walks", "leper", "sykes", "nerve", "rover", "jived", "brisk", "lenin", "viper", "chuck", "sinus", "luger", "ricks", "hying", "rusty", "kathy", "herds", "wider", "getty", "roman", "sandy", "pends", "fezes", "trios", "bites", "pants", "bless", "diced", "earth", "shack", "hinge", "melds", "jonah", "chose", "liver", "salts", "ratty", "ashed", "wacky", "yokes", "wanly", "bruce", "vowel", "black", "grail", "lungs", "arise", "gluts", "gluey", "navel", "coyer", "ramps", "miter", "aldan", "booth", "musty", "rills", "darns", "tined", "straw", "kerri", "hared", "lucks", "metes", "penny", "radon", "palms", "deeds", "earls", "shard", "pried", "tampa", "blank", "gybes", "vicki", "drool", "groom", "curer", "cubes", "riggs", "lanky", "tuber", "caves", "acing", "golly", "hodge", "beard", "ginny", "jibed", "fumes", "astor", "quito", "cargo", "randi", "gawky", "zings", "blind", "dhoti", "sneak", "fatah", "fixer", "lapps", "cline", "grimm", "fakes", "maine", "erika", "dealt", "mitch", "olden", "joist", "gents", "likes", "shelf", "silts", "goats", "leads", "marin", "spire", "louie", "evans", "amuse", "belly", "nails", "snead", "model", "whats", "shari", "quote", "tacks", "nutty", "lames", "caste", "hexes", "cooks", "miner", "shawn", "anise", "drama", "trike", "prate", "ayers", "loans", "botch", "vests", "cilia", "ridge", "thugs", "outed", "jails", "moped", "plead", "tunes", "nosed", "wills", "lager", "lacks", "cried", "wince", "berle", "flaws", "boise", "tibet", "bided", "shred", "cocky", "brice", "delta", "congo", "holly", "hicks", "wraps", "cocks", "aisha", "heard", "cured", "sades", "horsy", "umped", "trice", "dorky", "curve", "ferry", "haler", "ninth", "pasta", "jason", "honer", "kevin", "males", "fowls", "awake", "pores", "meter", "skate", "drink", "pussy", "soups", "bases", "noyes", "torts", "bogus", "still", "soupy", "dance", "worry", "eldon", "stern", "menes", "dolls", "dumpy", "gaunt", "grove", "coops", "mules", "berry", "sower", "roams", "brawl", "greed", "stags", "blurs", "swift", "treed", "taney", "shame", "easel", "moves", "leger", "ville", "order", "spock", "nifty", "brian", "elias", "idler", "serve", "ashen", "bizet", "gilts", "spook", "eaten", "pumas", "cotes", "broke", "toxin", "groan", "laths", "joins", "spots", "hated", "tokay", "elite", "rawer", "fiats", "cards", "sassy", "milks", "roost", "glean", "lutes", "chins", "drown", "marks", "pined", "grace", "fifth", "lodes", "rusts", "terms", "maxes", "savvy", "choir", "savoy", "spoon", "halve", "chord", "hulas", "sarah", "celia", "deems", "ninny", "wines", "boggy", "birch", "raved", "wales", "beams", "vibes", "riots", "warty", "nigel", "askew", "faxes", "sedge", "sheol", "pucks", "cynic", "relax", "boers", "whims", "bents", "candy", "luann", "slogs", "bonny", "barns", "iambs", "fused", "duffy", "guilt", "bruin", "pawls", "penis", "poppy", "owing", "tribe", "tuner", "moray", "timid", "ceded", "geeks", "kites", "curio", "puffy", "perot", "caddy", "peeve", "cause", "dills", "gavel", "manse", "joker", "lynch", "crank", "golda", "waits", "wises", "hasty", "paves", "grown", "reedy", "crypt", "tonne", "jerky", "axing", "swept", "posse", "rings", "staff", "tansy", "pared", "glaze", "grebe", "gonna", "shark", "jumps", "vials", "unset", "hires", "tying", "lured", "motes", "linen", "locks", "mamas", "nasty", "mamie", "clout", "nader", "velma", "abate", "tight", "dales", "serer", "rives", "bales", "loamy", "warps", "plato", "hooch", "togae", "damps", "ofter", "plumb", "fifes", "filmy", "wiper", "chess", "lousy", "sails", "brahe", "ounce", "flits", "hindu", "manly", "beaux", "mimed", "liken", "forts", "jambs", "peeps", "lelia", "brews", "handy", "lusty", "brads", "marne", "pesos", "earle", "arson", "scout", "showy", "chile", "sumps", "hiked", "crook", "herbs", "silks", "alamo", "mores", "dunce", "blaze", "stank", "haste", "howls", "trots", "creon", "lisle", "pause", "hates", "mulch", "mined", "moder", "devin", "types", "cindy", "beech", "tuned", "mowed", "pitts", "chaos", "colds", "bidet", "tines", "sighs", "slimy", "brain", "belle", "leery", "morse", "ruben", "prows", "frown", "disco", "regal", "oaken", "sheds", "hives", "corny", "baser", "fated", "throe", "revel", "bores", "waved", "shits", "elvia", "ferns", "maids", "color", "coifs", "cohan", "draft", "hmong", "alton", "stine", "cluck", "nodes", "emily", "brave", "blair", "blued", "dress", "bunts", "holst", "clogs", "rally", "knack", "demos", "brady", "blues", "flash", "goofy", "blocs", "diane", "colic", "smile", "yules", "foamy", "splay", "bilge", "faker", "foils", "condo", "knell", "crack", "gallo", "purls", "auras", "cakes", "doves", "joust", "aides", "lades", "muggy", "tanks", "middy", "tarps", "slack", "capet", "frays", "donny", "venal", "yeats", "misty", "denim", "glass", "nudes", "seeps", "gibbs", "blows", "bobbi", "shane", "yards", "pimps", "clued", "quiet", "witch", "boxes", "prawn", "kerry", "torah", "kinko", "dingy", "emote", "honor", "jelly", "grins", "trope", "vined", "bagel", "arden", "rapid", "paged", "loved", "agape", "mural", "budge", "ticks", "suers", "wendi", "slice", "salve", "robin", "bleat", "batik", "myles", "teddy", "flatt", "puppy", "gelid", "largo", "attar", "polls", "glide", "serum", "fundy", "sucks", "shalt", "sewer", "wreak", "dames", "fonts", "toxic", "hines", "wormy", "grass", "louse", "bowls", "crass", "benny", "moire", "margo", "golfs", "smart", "roxie", "wight", "reign", "dairy", "clops", "paled", "oddly", "sappy", "flair", "shown", "bulgy", "benet", "larch", "curry", "gulfs", "fends", "lunch", "dukes", "doris", "spoke", "coins", "manna", "conga", "jinns", "eases", "dunno", "tisha", "swore", "rhino", "calms", "irvin", "clans", "gully", "liege", "mains", "besot", "serge", "being", "welch", "wombs", "draco", "lynda", "forty", "mumps", "bloch", "ogden", "knits", "fussy", "alder", "danes", "loyal", "valet", "wooer", "quire", "liefs", "shana", "toyed", "forks", "gages", "slims", "cloys", "yates", "rails", "sheep", "nacho", "divan", "honks", "stone", "snack", "added", "basal", "hasps", "focus", "alone", "laxes", "arose", "lamed", "wrapt", "frail", "clams", "plait", "hover", "tacos", "mooch", "fault", "teeth", "marva", "mucks", "tread", "waves", "purim", "boron", "horde", "smack", "bongo", "monte", "swirl", "deals", "mikes", "scold", "muter", "sties", "lawns", "fluke", "jilts", "meuse", "fives", "sulky", "molds", "snore", "timmy", "ditty", "gasps", "kills", "carey", "jawed", "byers", "tommy", "homer", "hexed", "dumas", "given", "mewls", "smelt", "weird", "speck", "merck", "keats", "draws", "trent", "agave", "wells", "chews", "blabs", "roves", "grieg", "evens", "alive", "mulls", "cared", "garbo", "fined", "happy", "trued", "rodes", "thurs", "cadet", "alvin", "busch", "moths", "guild", "staci", "lever", "widen", "props", "hussy", "lamer", "riley", "bauer", "chirp", "rants", "poxes", "shyer", "pelts", "funny", "slits", "tinge", "ramos", "shift", "caper", "credo", "renal", "veils", "covey", "elmer", "mated", "tykes", "wooed", "briar", "gears", "foley", "shoes", "decry", "hypes", "dells", "wilds", "runts", "wilts", "white", "easts", "comer", "sammy", "lochs", "favor", "lance", "dawns", "bushy", "muted", "elsie", "creel", "pocks", "tenet", "cagey", "rides", "socks", "ogled", "soils", "sofas", "janna", "exile", "barks", "frank", "takes", "zooms", "hakes", "sagan", "scull", "heaps", "augur", "pouch", "blare", "bulbs", "wryly", "homey", "tubas", "limbo", "hardy", "hoagy", "minds", "bared", "gabby", "bilks", "float", "limns", "clasp", "laura", "range", "brush", "tummy", "kilts", "cooed", "worms", "leary", "feats", "robes", "suite", "veals", "bosch", "moans", "dozen", "rarer", "slyer", "cabin", "craze", "sweet", "talon", "treat", "yanks", "react", "creed", "eliza", "sluts", "cruet", "hafts", "noise", "seder", "flies", "weeks", "venus", "backs", "eider", "uriel", "vouch", "robed", "hacks", "perth", "shiny", "stilt", "torte", "throb", "merer", "twits", "reeds", "shawl", "clara", "slurs", "mixer", "newts", "fried", "woolf", "swoop", "kaaba", "oozed", "mayer", "caned", "laius", "lunge", "chits", "kenny", "lifts", "mafia", "sowed", "piled", "stein", "whack", "colts", "warms", "cleft", "girds", "seeks", "poets", "angel", "trade", "parsi", "tiers", "rojas", "vexes", "bryce", "moots", "grunt", "drain", "lumpy", "stabs", "poohs", "leapt", "polly", "cuffs", "giddy", "towns", "dacha", "quoth", "provo", "dilly", "carly", "mewed", "tzars", "crock", "toked", "speak", "mayas", "pssts", "ocher", "motel", "vogue", "camps", "tharp", "taunt", "drone", "taint", "badge", "scott", "scats", "bakes", "antes", "gruel", "snort", "capes", "plate", "folly", "adobe", "yours", "papaw", "hench", "moods", "clunk", "chevy", "tomas", "narcs", "vonda", "wiles", "prigs", "chock", "laser", "viced", "stiff", "rouse", "helps", "knead", "gazer", "blade", "tumid", "avail", "anger", "egged", "guide", "goads", "rabin", "toddy", "gulps", "flank", "brats", "pedal", "junky", "marco", "tinny", "tires", "flier", "satin", "darth", "paley", "gumbo", "rared", "muffs", "rower", "prude", "frees", "quays", "homes", "munch", "beefs", "leash", "aston", "colon", "finch", "bogey", "leaps", "tempo", "posts", "lined", "gapes", "locus", "maori", "nixes", "liven", "songs", "opted", "babel", "wader", "barer", "farts", "lisps", "koran", "lathe", "trill", "smirk", "mamma", "viler", "scurf", "ravel", "brigs", "cooky", "sachs", "fulls", "goals", "turfs", "norse", "hauls", "cores", "fairy", "pluto", "kneed", "cheek", "pangs", "risen", "czars", "milne", "cribs", "genes", "wefts", "vents", "sages", "seres", "owens", "wiley", "flume", "haded", "auger", "tatty", "onion", "cater", "wolfe", "magic", "bodes", "gulls", "gazes", "dandy", "snags", "rowed", "quell", "spurn", "shore", "veldt", "turns", "slavs", "coach", "stalk", "snuck", "piles", "orate", "joyed", "daily", "crone", "wager", "solos", "earns", "stark", "lauds", "kasey", "villa", "gnaws", "scent", "wears", "fains", "laced", "tamer", "pipes", "plant", "lorie", "rivet", "tamed", "cozen", "theme", "lifer", "sunny", "shags", "flack", "gassy", "eased", "jeeps", "shire", "fargo", "timer", "brash", "behan", "basin", "volga", "krone", "swiss", "docks", "booed", "ebert", "gusty", "delay", "oared", "grady", "buick", "curbs", "crete", "lucas", "strum", "besom", "gorse", "troth", "donne", "chink", "faced", "ahmed", "texas", "longs", "aloud", "bethe", "cacao", "hilda", "eagle", "karyn", "harks", "adder", "verse", "drays", "cello", "taped", "snide", "taxis", "kinky", "penes", "wicca", "sonja", "aways", "dyers", "bolas", "elfin", "slope", "lamps", "hutch", "lobed", "baaed", "masts", "ashes", "ionic", "joyce", "payed", "brays", "malts", "dregs", "leaky", "runny", "fecal", "woven", "hurls", "jorge", "henna", "dolby", "booty", "brett", "dykes", "rural", "fight", "feels", "flogs", "brunt", "preen", "elvis", "dopey", "gripe", "garry", "gamma", "fling", "space", "mange", "storm", "arron", "hairs", "rogue", "repel", "elgar", "ruddy", "cross", "medan", "loses", "howdy", "foams", "piker", "halts", "jewel", "avery", "stool", "cruel", "cases", "ruses", "cathy", "harem", "flour", "meted", "faces", "hobos", "charm", "jamar", "cameo", "crape", "hooey", "reefs", "denny", "mitts", "sores", "smoky", "nopes", "sooty", "twirl", "toads", "vader", "julep", "licks", "arias", "wrote", "north", "bunks", "heady", "batch", "snaps", "claws", "fouls", "faded", "beans", "wimps", "idled", "pulse", "goons", "noose", "vowed", "ronda", "rajas", "roast", "allah", "punic", "slows", "hours", "metal", "slier", "meaty", "hanna", "curvy", "mussy", "truth", "troys", "block", "reels", "print", "miffs", "busts", "bytes", "cream", "otter", "grads", "siren", "kilos", "dross", "batty", "debts", "sully", "bares", "baggy", "hippy", "berth", "gorky", "argon", "wacko", "harry", "smoke", "fails", "perms", "score", "steps", "unity", "couch", "kelly", "rumps", "fines", "mouth", "broth", "knows", "becky", "quits", "lauri", "trust", "grows", "logos", "apter", "burrs", "zincs", "buyer", "bayer", "moose", "overt", "croon", "ousts", "lands", "lithe", "poach", "jamel", "waive", "wiser", "surly", "works", "paine", "medal", "glads", "gybed", "paint", "lorre", "meant", "smugs", "bryon", "jinni", "sever", "viols", "flubs", "melts", "heads", "peals", "aiken", "named", "teary", "yalta", "styes", "heist", "bongs", "slops", "pouts", "grape", "belie", "cloak", "rocks", "scone", "lydia", "goofs", "rents", "drive", "crony", "orlon", "narks", "plays", "blips", "pence", "march", "alger", "baste", "acorn", "billy", "croce", "boone", "aaron", "slobs", "idyls", "irwin", "elves", "stoat", "doing", "globe", "verve", "icons", "trial", "olsen", "pecks", "there", "blame", "tilde", "milky", "sells", "tangy", "wrack", "fills", "lofty", "truce", "quark", "delia", "stowe", "marty", "overs", "putty", "coral", "swine", "stats", "swags", "weans", "spout", "bulky", "farsi", "brest", "gleam", "beaks", "coons", "hater", "peony", "huffy", "exert", "clips", "riven", "payer", "doped", "salas", "meyer", "dryad", "thuds", "tilts", "quilt", "jetty", "brood", "gulch", "corps", "tunic", "hubby", "slang", "wreck", "purrs", "punch", "drags", "chide", "sulks", "tints", "huger", "roped", "dopes", "booby", "rosin", "outer", "gusto", "tents", "elude", "brows", "lease", "ceres", "laxer", "worth", "necks", "races", "corey", "trait", "stuns", "soles", "teems", "scrip", "privy", "sight", "minor", "alisa", "stray", "spank", "cress", "nukes", "rises", "gusts", "aurae", "karma", "icing", "prose", "biked", "grand", "grasp", "skein", "shaky", "clump", "rummy", "stock", "twain", "zoned", "offed", "ghats", "mover", "randy", "vault", "craws", "thees", "salem", "downy", "sangs", "chore", "cited", "grave", "spinx", "erica", "raspy", "dying", "skips", "clerk", "paste", "moved", "rooks", "intel", "moses", "avers", "staid", "yawls", "blast", "lyres", "monks", "gaits", "floor", "saner", "waver", "assam", "infer", "wands", "bunch", "dryly", "weedy", "honey", "baths", "leach", "shorn", "shows", "dream", "value", "dooms", "spiro", "raped", "shook", "stead", "moran", "ditto", "loots", "tapir", "looms", "clove", "stops", "pinks", "soppy", "ripen", "wench", "shone", "bauds", "doric", "leans", "nadia", "cries", "camus", "boozy", "maris", "fools", "morns", "bides", "greek", "gauss", "roget", "lamar", "hazes", "beefy", "dupes", "refed", "felts", "larry", "guile", "ables", "wants", "warns", "toils", "bathe", "edger", "paced", "rinks", "shoos", "erich", "whore", "tiger", "jumpy", "lamas", "stack", "among", "punts", "scalp", "alloy", "solon", "quite", "comas", "whole", "parse", "tries", "reeve", "tiled", "deena", "roomy", "rodin", "aster", "twice", "musts", "globs", "parch", "drawn", "filch", "bonds", "tells", "droop", "janis", "holds", "scant", "lopes", "based", "keven", "whiny", "aspic", "gains", "franz", "jerri", "steel", "rowel", "vends", "yelps", "begin", "logic", "tress", "sunni", "going", "barge", "blood", "burns", "basks", "waifs", "bones", "skill", "hewer", "burly", "clime", "eking", "withs", "capek", "berta", "cheap", "films", "scoot", "tweed", "sizer", "wheat", "acton", "flung", "ponds", "tracy", "fiver", "berra", "roger", "mutes", "burke", "miked", "valve", "whisk", "runes", "parry", "toots", "japes", "roars", "rough", "irons", "romeo", "cages", "reeks", "cigar", "saiph", "dully", "hangs", "chops", "rolls", "prick", "acuff", "spent", "sulla", "train", "swell", "frets", "names", "anita", "crazy", "sixth", "blunt", "fewer", "large", "brand", "slick", "spitz", "rears", "ogres", "toffy", "yolks", "flock", "gnawn", "eries", "blink", "skier", "feted", "tones", "snail", "ether", "barbs", "noses", "hears", "upset", "awash", "cloud", "trunk", "degas", "dungs", "rated", "shall", "yeahs", "coven", "sands", "susan", "fable", "gunny", "began", "serfs", "balls", "dinky", "madge", "prong", "spilt", "lilly", "brawn", "comet", "spins", "raids", "dries", "sorts", "makes", "mason", "mayra", "royce", "stout", "mealy", "pagan", "nasal", "folds", "libby", "coups", "photo", "mosey", "amens", "speed", "lords", "board", "fetal", "lagos", "scope", "raked", "bonus", "mutts", "willy", "sport", "bingo", "thant", "araby", "bette", "rebel", "gases", "small", "humus", "grosz", "beset", "slays", "steve", "scrap", "blahs", "south", "pride", "heels", "tubes", "beady", "lacey", "genus", "mauls", "vying", "spice", "sexes", "ester", "drams", "today", "comae", "under", "jests", "direr", "yoked", "tempi", "early", "boats", "jesus", "warts", "guppy", "gilda", "quota", "token", "edwin", "ringo", "gaped", "lemon", "hurst", "manor", "arrow", "mists", "prize", "silas", "blobs", "diets", "ervin", "stony", "buddy", "bates", "rabid", "ducat", "ewing", "jaunt", "beads", "doyen", "blush", "thoth", "tiles", "piper", "short", "peron", "alley", "decks", "shunt", "whirs", "cushy", "roils", "betty", "plugs", "woken", "jibes", "foray", "merak", "ruing", "becks", "whale", "shoot", "dwelt", "spawn", "fairs", "dozed", "celts", "blond", "tikes", "sabin", "feint", "vamps", "cokes", "willa", "slues", "bills", "force", "curst", "yokel", "surer", "miler", "fices", "arced", "douse", "hilly", "lucio", "tongs", "togas", "minty", "sagas", "pates", "welsh", "bruno", "decal", "elate", "linux", "gyros", "pryor", "mousy", "pains", "shake", "spica", "pupal", "probe", "mount", "shirk", "purus", "kilns", "rests", "graze", "hague", "spuds", "sweep", "momma", "burch", "maces", "samar", "brace", "riser", "booms", "build", "camel", "flyer", "synge", "sauna", "tonga", "tings", "promo", "hides", "clair", "elisa", "bower", "reins", "diann", "lubed", "nulls", "picks", "laban", "milch", "buber", "stomp", "bosom", "lying", "haled", "avert", "wries", "macon", "skids", "fumed", "ogles", "clods", "antic", "nosey", "crimp", "purge", "mommy", "cased", "taxes", "covet", "clack", "butch", "panty", "lents", "machs", "exude", "tooth", "adore", "shuck", "asses", "after", "terra", "dices", "aryan", "regor", "romes", "stile", "cairo", "maura", "flail", "eaves", "estes", "sousa", "visas", "baron", "civet", "kitty", "freed", "ralph", "tango", "gawks", "cheat", "study", "fancy", "fiber", "musks", "souse", "brims", "claim", "bikes", "venue", "sired", "thymi", "rivas", "skimp", "pleas", "woman", "gimpy", "cawed", "minos", "pints", "knock", "poked", "bowen", "risky", "towel", "oinks", "linus", "heals", "pears", "codas", "inner", "pitch", "harpy", "niger", "madly", "bumpy", "stair", "files", "nobel", "celli", "spars", "jades", "balmy", "kooky", "plums", "trues", "gloss", "trims", "daunt", "tubby", "dared", "wadis", "smell", "darby", "stink", "drill", "dover", "ruler", "laden", "dikes", "layla", "fells", "maker", "joked", "horns", "these", "baize", "spahn", "whens", "edged", "mushy", "plume", "tucks", "spurs", "husky", "dried", "bigot", "pupas", "drily", "aware", "hagar", "newly", "knots", "pratt", "feces", "sabik", "watts", "cooke", "riles", "seamy", "fleas", "dusts", "barfs", "roans", "pawns", "vivid", "kirks", "tania", "feral", "tubae", "horne", "aries", "brits", "combs", "chunk", "stork", "waned", "texan", "elide", "glens", "emery", "autos", "trams", "dosed", "cheri", "baits", "jacks", "whose", "fazed", "matte", "swans", "maxed", "write", "spays", "orion", "traci", "horse", "stars", "strut", "goods", "verge", "scuff", "award", "dives", "wires", "burnt", "dimly", "sleds", "mayan", "biped", "quirk", "sofia", "slabs", "waste", "robby", "mayor", "fatty", "items", "bowel", "mires", "swarm", "route", "swash", "sooth", "paved", "steak", "upend", "sough", "throw", "perts", "stave", "carry", "burgs", "hilts", "plane", "toady", "nadir", "stick", "foist", "gnarl", "spain", "enter", "sises", "story", "scarf", "ryder", "glums", "nappy", "sixes", "honed", "marcy", "offer", "kneel", "leeds", "lites", "voter", "vince", "bursa", "heave", "roses", "trees", "argos", "leann", "grimy", "zelma", "crick", "tract", "flips", "folks", "smote", "brier", "moore", "goose", "baden", "riled", "looks", "sober", "tusks", "house", "acmes", "lubes", "chows", "neath", "vivas", "defer", "allay", "casey", "kmart", "pests", "proms", "eying", "cider", "leave", "shush", "shots", "karla", "scorn", "gifts", "sneer", "mercy", "copes", "faxed", "spurt", "monet", "awoke", "rocky", "share", "gores", "drawl", "tears", "mooed", "nones", "wined", "wrens", "modem", "beria", "hovel", "retch", "mates", "hands", "stymy", "peace", "carat", "coots", "hotel", "karen", "hayed", "mamet", "cuing", "paper", "rages", "suave", "reuse", "auden", "costs", "loner", "rapes", "hazel", "rites", "brent", "pumps", "dutch", "puffs", "noons", "grams", "teats", "cease", "honda", "pricy", "forgo", "fleck", "hired", "silos", "merge", "rafts", "halon", "larks", "deere", "jello", "cunts", "sifts", "boner", "morin", "mimes", "bungs", "marie", "harts", "snobs", "sonic", "hippo", "comes", "crops", "mango", "wrung", "garbs", "natty", "cents", "fitch", "moldy", "adams", "sorta", "coeds", "gilds", "kiddy", "nervy", "slurp", "ramon", "fuzed", "hiker", "winks", "vanes", "goody", "hawks", "crowd", "bract", "marla", "limbs", "solve", "gloom", "sloop", "eaton", "memos", "tames", "heirs", "berms", "wanes", "faint", "numbs", "holes", "grubs", "rakes", "waist", "miser", "stays", "antis", "marsh", "skyed", "payne", "champ", "jimmy", "clues", "fatal", "shoed", "freon", "lopez", "snowy", "loins", "stale", "thank", "reads", "isles", "grill", "align", "saxes", "rubin", "rigel", "walls", "beers", "wispy", "topic", "alden", "anton", "ducts", "david", "duets", "fries", "oiled", "waken", "allot", "swats", "woozy", "tuxes", "inter", "dunne", "known", "axles", "graph", "bumps", "jerry", "hitch", "crews", "lucia", "banal", "grope", "valid", "meres", "thick", "lofts", "chaff", "taker", "glues", "snubs", "trawl", "keels", "liker", "stand", "harps", "casks", "nelly", "debby", "panes", "dumps", "norma", "racks", "scams", "forte", "dwell", "dudes", "hypos", "sissy", "swamp", "faust", "slake", "maven", "lowed", "lilts", "bobby", "gorey", "swear", "nests", "marci", "palsy", "siege", "oozes", "rates", "stunt", "herod", "wilma", "other", "girts", "conic", "goner", "peppy", "class", "sized", "games", "snell", "newsy", "amend", "solis", "duane", "troop", "linda", "tails", "woofs", "scuds", "shies", "patti", "stunk", "acres", "tevet", "allen", "carpi", "meets", "trend", "salty", "galls", "crept", "toner", "panda", "cohen", "chase", "james", "bravo", "styed", "coals", "oates", "swami", "staph", "frisk", "cares", "cords", "stems", "razed", "since", "mopes", "rices", "junes", "raged", "liter", "manes", "rearm", "naive", "tyree", "medic", "laded", "pearl", "inset", "graft", "chair", "votes", "saver", "cains", "knobs", "gamay", "hunch", "crags", "olson", "teams", "surge", "wests", "boney", "limos", "ploys", "algae", "gaols", "caked", "molts", "glops", "tarot", "wheal", "cysts", "husks", "vaunt", "beaus", "fauns", "jeers", "mitty", "stuff", "shape", "sears", "buffy", "maced", "fazes", "vegas", "stamp", "borer", "gaged", "shade", "finds", "frock", "plods", "skied", "stump", "ripes", "chick", "cones", "fixed", "coled", "rodeo", "basil", "dazes", "sting", "surfs", "mindy", "creak", "swung", "cadge", "franc", "seven", "sices", "weest", "unite", "codex", "trick", "fusty", "plaid", "hills", "truck", "spiel", "sleek", "anons", "pupae", "chiba", "hoops", "trash", "noted", "boris", "dough", "shirt", "cowls", "seine", "spool", "miens", "yummy", "grade", "proxy", "hopes", "girth", "deter", "dowry", "aorta", "paean", "corms", "giant", "shank", "where", "means", "years", "vegan", "derek", "tales"]; +$s = new Solution(); +$ret = $s->ladderLength($beginWord, $endWord, $wordList); +print_r($ret); \ No newline at end of file From dbca7ef36cfff8031383886a344650c5ea1c59a0 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Tue, 8 Dec 2020 17:20:50 +0800 Subject: [PATCH 092/192] =?UTF-8?q?=E5=8D=95=E8=AF=8D=E6=8E=A5=E9=BE=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week4/126.word-ladder-ii.php | 206 +++++++++++++++++++++++++++++++++++ 1 file changed, 206 insertions(+) create mode 100644 Week4/126.word-ladder-ii.php diff --git a/Week4/126.word-ladder-ii.php b/Week4/126.word-ladder-ii.php new file mode 100644 index 00000000..74433fb8 --- /dev/null +++ b/Week4/126.word-ladder-ii.php @@ -0,0 +1,206 @@ +enqueue([$beginWord, $level]); + $visited = [$beginWord]; + + $wordMap[$beginWord][] = $beginWord; + + while (!$queue->isEmpty()) { + list($curWord, $level) = $queue->dequeue(); + if ($curWord == $endWord) $canFinish = true; + $levelMap[$curWord] = $level; + for ($i = 0; $i < strlen($curWord); $i++) { + for ($j = 'a'; $j <= 'z'; $j++) { + $nextWord = $curWord; + $nextWord[$i] = $j; + if (isset($newWordList[$nextWord])) { + if (!isset($wordMap[$curWord])) { + $wordMap[$curWord][] = $nextWord; + } elseif (!in_array($nextWord, $wordMap[$curWord])) { + $wordMap[$curWord][] = $nextWord; + } + if (in_array($nextWord, $visited)) continue; + $queue->enqueue([$nextWord, $level + 1]); + $visited[] = $nextWord; + } + } + } + } +// print_r($wordMap); +// print_r($levelMap); + $res = []; + $this->dfs($wordMap, $levelMap, $endWord, $beginWord, [], $res); + return $res; + } + + function dfs($wordMap, $levelMap, $endWord, $word, $path, &$res) + { + array_push($path, $word); + if ($word == $endWord) { + $res[] = $path; + return; + } + foreach ($wordMap[$word] as $nextWord) { + if ($levelMap[$word] + 1 == $levelMap[$nextWord]) { + $this->dfs($wordMap, $levelMap, $endWord, $nextWord, $path, $res); + } + } + array_pop($path); + } + + + /** + * @param String $beginWord + * @param String $endWord + * @param String[] $wordList + * @return String[][] + */ + function findLadders2($beginWord, $endWord, $wordList) + { + $wordId = []; + $idWord = []; + + // 将wordList所有单词加入wordId中 相同的只保留一个 // 并为每一个单词分配一个id + $id = 0; + for ($i = 0; $i < count($wordList); $i++) { + if (!isset($wordId[$wordList[$i]])) { + $wordId[$wordList[$i]] = $id++; + $idWord[] = $wordList[$i]; + } + } + + // 若endWord不在wordList中 则无解 + if (!isset($wordId[$endWord])) { + return []; + } + + // 把beginWord也加入wordId中 + if (!isset($wordId[$beginWord])) { + $wordId[$beginWord] = $id++; + $idWord[] = $beginWord; + } + + $edges = array_fill(0, count($wordId), []); + //构建边 无向图 + for ($i = 0; $i < count($idWord); $i++) { + for ($j = $i + 1; $j < count($idWord); $j++) { + if ($this->transformCheck($idWord[$i], $idWord[$j])) { + $edges[$i][] = $j; + $edges[$j][] = $i; + } + } + } + +// print_r($idWord); +// print_r($wordId); + //print_r($edges); + $inf = (1 << 20); + $cost = array_fill(0, count($idWord), $inf); //cost[i] 代表 i的点 到 beginWord的点 的距离 + $res = []; + $dest = $wordId[$endWord]; + //print_r('dest:' . $dest . PHP_EOL); + $cost[$wordId[$beginWord]] = 0; + $queue = new SplQueue(); + $path = [$wordId[$beginWord]]; + $queue->enqueue($path); + while (!$queue->isEmpty()) { + $curPath = $queue->dequeue(); + $last = end($curPath); + if ($last == $dest) { + $res[] = array_map(function ($v) use ($idWord) { + return $idWord[$v]; + }, $curPath); + } else { + foreach ($edges[$last] as $to) { +// print_r('last:' . $last . '|to:' . $to . PHP_EOL); +// print_r($cost); + if ($cost[$last] + 1 <= $cost[$to]) { + $cost[$to] = $cost[$last] + 1; + $nextPath = $curPath; + $nextPath[] = $to; + $queue->enqueue($nextPath); + } + } + } + } + return $res; + } + + function transformCheck($word1, $word2) + { + $diff = 0; + for ($i = 0; $i < strlen($word1); $i++) { + if ($word1[$i] != $word2[$i]) { + if (++$diff != 1) { + return false; + } + } + } + return true; + } + + +} + +$wordMap = [ + 'hit' => ['hit', 'hot'], + 'hot' => ['hit', 'hot', 'dot', 'lot'], + 'dot' => ['hot', 'dot', 'lot', 'dog'], + 'lot' => ['hot', 'dot', 'lot', 'log'], + 'dog' => ['dot', 'dog', 'log', 'cog'], + 'log' => ['lot', 'dog', 'log', 'log', 'cog'], + 'cog' => ['dog', 'log', 'cog'] +]; +$wordMap = [ + 'hit' => ['hit', 'hot'], + 'hot' => ['dot', 'lot'], + 'dot' => ['dog'], + 'lot' => ['log'], + 'dog' => ['cog'], +]; +$levelMap = [ + 'hit' => 1, + 'hot' => 2, + 'dot' => 3, + 'lot' => 3, + 'dog' => 4, + 'log' => 4, + 'cog' => 5 +]; + +$beginWord = 'sand'; +$endWord = 'acne'; +$wordList = ["slit", "bunk", "wars", "ping", "viva", "wynn", "wows", "irks", "gang", "pool", "mock", "fort", "heel", "send", "ship", "cols", "alec", "foal", "nabs", "gaze", "giza", "mays", "dogs", "karo", "cums", "jedi", "webb", "lend", "mire", "jose", "catt", "grow", "toss", "magi", "leis", "bead", "kara", "hoof", "than", "ires", "baas", "vein", "kari", "riga", "oars", "gags", "thug", "yawn", "wive", "view", "germ", "flab", "july", "tuck", "rory", "bean", "feed", "rhee", "jeez", "gobs", "lath", "desk", "yoko", "cute", "zeus", "thus", "dims", "link", "dirt", "mara", "disc", "limy", "lewd", "maud", "duly", "elsa", "hart", "rays", "rues", "camp", "lack", "okra", "tome", "math", "plug", "monk", "orly", "friz", "hogs", "yoda", "poop", "tick", "plod", "cloy", "pees", "imps", "lead", "pope", "mall", "frey", "been", "plea", "poll", "male", "teak", "soho", "glob", "bell", "mary", "hail", "scan", "yips", "like", "mull", "kory", "odor", "byte", "kaye", "word", "honk", "asks", "slid", "hopi", "toke", "gore", "flew", "tins", "mown", "oise", "hall", "vega", "sing", "fool", "boat", "bobs", "lain", "soft", "hard", "rots", "sees", "apex", "chan", "told", "woos", "unit", "scow", "gilt", "beef", "jars", "tyre", "imus", "neon", "soap", "dabs", "rein", "ovid", "hose", "husk", "loll", "asia", "cope", "tail", "hazy", "clad", "lash", "sags", "moll", "eddy", "fuel", "lift", "flog", "land", "sigh", "saks", "sail", "hook", "visa", "tier", "maws", "roeg", "gila", "eyes", "noah", "hypo", "tore", "eggs", "rove", "chap", "room", "wait", "lurk", "race", "host", "dada", "lola", "gabs", "sobs", "joel", "keck", "axed", "mead", "gust", "laid", "ends", "oort", "nose", "peer", "kept", "abet", "iran", "mick", "dead", "hags", "tens", "gown", "sick", "odis", "miro", "bill", "fawn", "sumo", "kilt", "huge", "ores", "oran", "flag", "tost", "seth", "sift", "poet", "reds", "pips", "cape", "togo", "wale", "limn", "toll", "ploy", "inns", "snag", "hoes", "jerk", "flux", "fido", "zane", "arab", "gamy", "raze", "lank", "hurt", "rail", "hind", "hoot", "dogy", "away", "pest", "hoed", "pose", "lose", "pole", "alva", "dino", "kind", "clan", "dips", "soup", "veto", "edna", "damp", "gush", "amen", "wits", "pubs", "fuzz", "cash", "pine", "trod", "gunk", "nude", "lost", "rite", "cory", "walt", "mica", "cart", "avow", "wind", "book", "leon", "life", "bang", "draw", "leek", "skis", "dram", "ripe", "mine", "urea", "tiff", "over", "gale", "weir", "defy", "norm", "tull", "whiz", "gill", "ward", "crag", "when", "mill", "firs", "sans", "flue", "reid", "ekes", "jain", "mutt", "hems", "laps", "piss", "pall", "rowe", "prey", "cull", "knew", "size", "wets", "hurl", "wont", "suva", "girt", "prys", "prow", "warn", "naps", "gong", "thru", "livy", "boar", "sade", "amok", "vice", "slat", "emir", "jade", "karl", "loyd", "cerf", "bess", "loss", "rums", "lats", "bode", "subs", "muss", "maim", "kits", "thin", "york", "punt", "gays", "alpo", "aids", "drag", "eras", "mats", "pyre", "clot", "step", "oath", "lout", "wary", "carp", "hums", "tang", "pout", "whip", "fled", "omar", "such", "kano", "jake", "stan", "loop", "fuss", "mini", "byrd", "exit", "fizz", "lire", "emil", "prop", "noes", "awed", "gift", "soli", "sale", "gage", "orin", "slur", "limp", "saar", "arks", "mast", "gnat", "port", "into", "geed", "pave", "awls", "cent", "cunt", "full", "dint", "hank", "mate", "coin", "tars", "scud", "veer", "coax", "bops", "uris", "loom", "shod", "crib", "lids", "drys", "fish", "edit", "dick", "erna", "else", "hahs", "alga", "moho", "wire", "fora", "tums", "ruth", "bets", "duns", "mold", "mush", "swop", "ruby", "bolt", "nave", "kite", "ahem", "brad", "tern", "nips", "whew", "bait", "ooze", "gino", "yuck", "drum", "shoe", "lobe", "dusk", "cult", "paws", "anew", "dado", "nook", "half", "lams", "rich", "cato", "java", "kemp", "vain", "fees", "sham", "auks", "gish", "fire", "elam", "salt", "sour", "loth", "whit", "yogi", "shes", "scam", "yous", "lucy", "inez", "geld", "whig", "thee", "kelp", "loaf", "harm", "tomb", "ever", "airs", "page", "laud", "stun", "paid", "goop", "cobs", "judy", "grab", "doha", "crew", "item", "fogs", "tong", "blip", "vest", "bran", "wend", "bawl", "feel", "jets", "mixt", "tell", "dire", "devi", "milo", "deng", "yews", "weak", "mark", "doug", "fare", "rigs", "poke", "hies", "sian", "suez", "quip", "kens", "lass", "zips", "elva", "brat", "cosy", "teri", "hull", "spun", "russ", "pupa", "weed", "pulp", "main", "grim", "hone", "cord", "barf", "olav", "gaps", "rote", "wilt", "lars", "roll", "balm", "jana", "give", "eire", "faun", "suck", "kegs", "nita", "weer", "tush", "spry", "loge", "nays", "heir", "dope", "roar", "peep", "nags", "ates", "bane", "seas", "sign", "fred", "they", "lien", "kiev", "fops", "said", "lawn", "lind", "miff", "mass", "trig", "sins", "furl", "ruin", "sent", "cray", "maya", "clog", "puns", "silk", "axis", "grog", "jots", "dyer", "mope", "rand", "vend", "keen", "chou", "dose", "rain", "eats", "sped", "maui", "evan", "time", "todd", "skit", "lief", "sops", "outs", "moot", "faze", "biro", "gook", "fill", "oval", "skew", "veil", "born", "slob", "hyde", "twin", "eloy", "beat", "ergs", "sure", "kobe", "eggo", "hens", "jive", "flax", "mons", "dunk", "yest", "begs", "dial", "lodz", "burp", "pile", "much", "dock", "rene", "sago", "racy", "have", "yalu", "glow", "move", "peps", "hods", "kins", "salk", "hand", "cons", "dare", "myra", "sega", "type", "mari", "pelt", "hula", "gulf", "jugs", "flay", "fest", "spat", "toms", "zeno", "taps", "deny", "swag", "afro", "baud", "jabs", "smut", "egos", "lara", "toes", "song", "fray", "luis", "brut", "olen", "mere", "ruff", "slum", "glad", "buds", "silt", "rued", "gelt", "hive", "teem", "ides", "sink", "ands", "wisp", "omen", "lyre", "yuks", "curb", "loam", "darn", "liar", "pugs", "pane", "carl", "sang", "scar", "zeds", "claw", "berg", "hits", "mile", "lite", "khan", "erik", "slug", "loon", "dena", "ruse", "talk", "tusk", "gaol", "tads", "beds", "sock", "howe", "gave", "snob", "ahab", "part", "meir", "jell", "stir", "tels", "spit", "hash", "omit", "jinx", "lyra", "puck", "laue", "beep", "eros", "owed", "cede", "brew", "slue", "mitt", "jest", "lynx", "wads", "gena", "dank", "volt", "gray", "pony", "veld", "bask", "fens", "argo", "work", "taxi", "afar", "boon", "lube", "pass", "lazy", "mist", "blot", "mach", "poky", "rams", "sits", "rend", "dome", "pray", "duck", "hers", "lure", "keep", "gory", "chat", "runt", "jams", "lays", "posy", "bats", "hoff", "rock", "keri", "raul", "yves", "lama", "ramp", "vote", "jody", "pock", "gist", "sass", "iago", "coos", "rank", "lowe", "vows", "koch", "taco", "jinn", "juno", "rape", "band", "aces", "goal", "huck", "lila", "tuft", "swan", "blab", "leda", "gems", "hide", "tack", "porn", "scum", "frat", "plum", "duds", "shad", "arms", "pare", "chin", "gain", "knee", "foot", "line", "dove", "vera", "jays", "fund", "reno", "skid", "boys", "corn", "gwyn", "sash", "weld", "ruiz", "dior", "jess", "leaf", "pars", "cote", "zing", "scat", "nice", "dart", "only", "owls", "hike", "trey", "whys", "ding", "klan", "ross", "barb", "ants", "lean", "dopy", "hock", "tour", "grip", "aldo", "whim", "prom", "rear", "dins", "duff", "dell", "loch", "lava", "sung", "yank", "thar", "curl", "venn", "blow", "pomp", "heat", "trap", "dali", "nets", "seen", "gash", "twig", "dads", "emmy", "rhea", "navy", "haws", "mite", "bows", "alas", "ives", "play", "soon", "doll", "chum", "ajar", "foam", "call", "puke", "kris", "wily", "came", "ales", "reef", "raid", "diet", "prod", "prut", "loot", "soar", "coed", "celt", "seam", "dray", "lump", "jags", "nods", "sole", "kink", "peso", "howl", "cost", "tsar", "uric", "sore", "woes", "sewn", "sake", "cask", "caps", "burl", "tame", "bulk", "neva", "from", "meet", "webs", "spar", "fuck", "buoy", "wept", "west", "dual", "pica", "sold", "seed", "gads", "riff", "neck", "deed", "rudy", "drop", "vale", "flit", "romp", "peak", "jape", "jews", "fain", "dens", "hugo", "elba", "mink", "town", "clam", "feud", "fern", "dung", "newt", "mime", "deem", "inti", "gigs", "sosa", "lope", "lard", "cara", "smug", "lego", "flex", "doth", "paar", "moon", "wren", "tale", "kant", "eels", "muck", "toga", "zens", "lops", "duet", "coil", "gall", "teal", "glib", "muir", "ails", "boer", "them", "rake", "conn", "neat", "frog", "trip", "coma", "must", "mono", "lira", "craw", "sled", "wear", "toby", "reel", "hips", "nate", "pump", "mont", "died", "moss", "lair", "jibe", "oils", "pied", "hobs", "cads", "haze", "muse", "cogs", "figs", "cues", "roes", "whet", "boru", "cozy", "amos", "tans", "news", "hake", "cots", "boas", "tutu", "wavy", "pipe", "typo", "albs", "boom", "dyke", "wail", "woke", "ware", "rita", "fail", "slab", "owes", "jane", "rack", "hell", "lags", "mend", "mask", "hume", "wane", "acne", "team", "holy", "runs", "exes", "dole", "trim", "zola", "trek", "puma", "wacs", "veep", "yaps", "sums", "lush", "tubs", "most", "witt", "bong", "rule", "hear", "awry", "sots", "nils", "bash", "gasp", "inch", "pens", "fies", "juts", "pate", "vine", "zulu", "this", "bare", "veal", "josh", "reek", "ours", "cowl", "club", "farm", "teat", "coat", "dish", "fore", "weft", "exam", "vlad", "floe", "beak", "lane", "ella", "warp", "goth", "ming", "pits", "rent", "tito", "wish", "amps", "says", "hawk", "ways", "punk", "nark", "cagy", "east", "paul", "bose", "solo", "teed", "text", "hews", "snip", "lips", "emit", "orgy", "icon", "tuna", "soul", "kurd", "clod", "calk", "aunt", "bake", "copy", "acid", "duse", "kiln", "spec", "fans", "bani", "irma", "pads", "batu", "logo", "pack", "oder", "atop", "funk", "gide", "bede", "bibs", "taut", "guns", "dana", "puff", "lyme", "flat", "lake", "june", "sets", "gull", "hops", "earn", "clip", "fell", "kama", "seal", "diaz", "cite", "chew", "cuba", "bury", "yard", "bank", "byes", "apia", "cree", "nosh", "judo", "walk", "tape", "taro", "boot", "cods", "lade", "cong", "deft", "slim", "jeri", "rile", "park", "aeon", "fact", "slow", "goff", "cane", "earp", "tart", "does", "acts", "hope", "cant", "buts", "shin", "dude", "ergo", "mode", "gene", "lept", "chen", "beta", "eden", "pang", "saab", "fang", "whir", "cove", "perk", "fads", "rugs", "herb", "putt", "nous", "vane", "corm", "stay", "bids", "vela", "roof", "isms", "sics", "gone", "swum", "wiry", "cram", "rink", "pert", "heap", "sikh", "dais", "cell", "peel", "nuke", "buss", "rasp", "none", "slut", "bent", "dams", "serb", "dork", "bays", "kale", "cora", "wake", "welt", "rind", "trot", "sloe", "pity", "rout", "eves", "fats", "furs", "pogo", "beth", "hued", "edam", "iamb", "glee", "lute", "keel", "airy", "easy", "tire", "rube", "bogy", "sine", "chop", "rood", "elbe", "mike", "garb", "jill", "gaul", "chit", "dons", "bars", "ride", "beck", "toad", "make", "head", "suds", "pike", "snot", "swat", "peed", "same", "gaza", "lent", "gait", "gael", "elks", "hang", "nerf", "rosy", "shut", "glop", "pain", "dion", "deaf", "hero", "doer", "wost", "wage", "wash", "pats", "narc", "ions", "dice", "quay", "vied", "eons", "case", "pour", "urns", "reva", "rags", "aden", "bone", "rang", "aura", "iraq", "toot", "rome", "hals", "megs", "pond", "john", "yeps", "pawl", "warm", "bird", "tint", "jowl", "gibe", "come", "hold", "pail", "wipe", "bike", "rips", "eery", "kent", "hims", "inks", "fink", "mott", "ices", "macy", "serf", "keys", "tarp", "cops", "sods", "feet", "tear", "benz", "buys", "colo", "boil", "sews", "enos", "watt", "pull", "brag", "cork", "save", "mint", "feat", "jamb", "rubs", "roxy", "toys", "nosy", "yowl", "tamp", "lobs", "foul", "doom", "sown", "pigs", "hemp", "fame", "boor", "cube", "tops", "loco", "lads", "eyre", "alta", "aged", "flop", "pram", "lesa", "sawn", "plow", "aral", "load", "lied", "pled", "boob", "bert", "rows", "zits", "rick", "hint", "dido", "fist", "marc", "wuss", "node", "smog", "nora", "shim", "glut", "bale", "perl", "what", "tort", "meek", "brie", "bind", "cake", "psst", "dour", "jove", "tree", "chip", "stud", "thou", "mobs", "sows", "opts", "diva", "perm", "wise", "cuds", "sols", "alan", "mild", "pure", "gail", "wins", "offs", "nile", "yelp", "minn", "tors", "tran", "homy", "sadr", "erse", "nero", "scab", "finn", "mich", "turd", "then", "poem", "noun", "oxus", "brow", "door", "saws", "eben", "wart", "wand", "rosa", "left", "lina", "cabs", "rapt", "olin", "suet", "kalb", "mans", "dawn", "riel", "temp", "chug", "peal", "drew", "null", "hath", "many", "took", "fond", "gate", "sate", "leak", "zany", "vans", "mart", "hess", "home", "long", "dirk", "bile", "lace", "moog", "axes", "zone", "fork", "duct", "rico", "rife", "deep", "tiny", "hugh", "bilk", "waft", "swig", "pans", "with", "kern", "busy", "film", "lulu", "king", "lord", "veda", "tray", "legs", "soot", "ells", "wasp", "hunt", "earl", "ouch", "diem", "yell", "pegs", "blvd", "polk", "soda", "zorn", "liza", "slop", "week", "kill", "rusk", "eric", "sump", "haul", "rims", "crop", "blob", "face", "bins", "read", "care", "pele", "ritz", "beau", "golf", "drip", "dike", "stab", "jibs", "hove", "junk", "hoax", "tats", "fief", "quad", "peat", "ream", "hats", "root", "flak", "grit", "clap", "pugh", "bosh", "lock", "mute", "crow", "iced", "lisa", "bela", "fems", "oxes", "vies", "gybe", "huff", "bull", "cuss", "sunk", "pups", "fobs", "turf", "sect", "atom", "debt", "sane", "writ", "anon", "mayo", "aria", "seer", "thor", "brim", "gawk", "jack", "jazz", "menu", "yolk", "surf", "libs", "lets", "bans", "toil", "open", "aced", "poor", "mess", "wham", "fran", "gina", "dote", "love", "mood", "pale", "reps", "ines", "shot", "alar", "twit", "site", "dill", "yoga", "sear", "vamp", "abel", "lieu", "cuff", "orbs", "rose", "tank", "gape", "guam", "adar", "vole", "your", "dean", "dear", "hebe", "crab", "hump", "mole", "vase", "rode", "dash", "sera", "balk", "lela", "inca", "gaea", "bush", "loud", "pies", "aide", "blew", "mien", "side", "kerr", "ring", "tess", "prep", "rant", "lugs", "hobo", "joke", "odds", "yule", "aida", "true", "pone", "lode", "nona", "weep", "coda", "elmo", "skim", "wink", "bras", "pier", "bung", "pets", "tabs", "ryan", "jock", "body", "sofa", "joey", "zion", "mace", "kick", "vile", "leno", "bali", "fart", "that", "redo", "ills", "jogs", "pent", "drub", "slaw", "tide", "lena", "seep", "gyps", "wave", "amid", "fear", "ties", "flan", "wimp", "kali", "shun", "crap", "sage", "rune", "logs", "cain", "digs", "abut", "obit", "paps", "rids", "fair", "hack", "huns", "road", "caws", "curt", "jute", "fisk", "fowl", "duty", "holt", "miss", "rude", "vito", "baal", "ural", "mann", "mind", "belt", "clem", "last", "musk", "roam", "abed", "days", "bore", "fuze", "fall", "pict", "dump", "dies", "fiat", "vent", "pork", "eyed", "docs", "rive", "spas", "rope", "ariz", "tout", "game", "jump", "blur", "anti", "lisp", "turn", "sand", "food", "moos", "hoop", "saul", "arch", "fury", "rise", "diss", "hubs", "burs", "grid", "ilks", "suns", "flea", "soil", "lung", "want", "nola", "fins", "thud", "kidd", "juan", "heps", "nape", "rash", "burt", "bump", "tots", "brit", "mums", "bole", "shah", "tees", "skip", "limb", "umps", "ache", "arcs", "raft", "halo", "luce", "bahs", "leta", "conk", "duos", "siva", "went", "peek", "sulk", "reap", "free", "dubs", "lang", "toto", "hasp", "ball", "rats", "nair", "myst", "wang", "snug", "nash", "laos", "ante", "opal", "tina", "pore", "bite", "haas", "myth", "yugo", "foci", "dent", "bade", "pear", "mods", "auto", "shop", "etch", "lyly", "curs", "aron", "slew", "tyro", "sack", "wade", "clio", "gyro", "butt", "icky", "char", "itch", "halt", "gals", "yang", "tend", "pact", "bees", "suit", "puny", "hows", "nina", "brno", "oops", "lick", "sons", "kilo", "bust", "nome", "mona", "dull", "join", "hour", "papa", "stag", "bern", "wove", "lull", "slip", "laze", "roil", "alto", "bath", "buck", "alma", "anus", "evil", "dumb", "oreo", "rare", "near", "cure", "isis", "hill", "kyle", "pace", "comb", "nits", "flip", "clop", "mort", "thea", "wall", "kiel", "judd", "coop", "dave", "very", "amie", "blah", "flub", "talc", "bold", "fogy", "idea", "prof", "horn", "shoo", "aped", "pins", "helm", "wees", "beer", "womb", "clue", "alba", "aloe", "fine", "bard", "limo", "shaw", "pint", "swim", "dust", "indy", "hale", "cats", "troy", "wens", "luke", "vern", "deli", "both", "brig", "daub", "sara", "sued", "bier", "noel", "olga", "dupe", "look", "pisa", "knox", "murk", "dame", "matt", "gold", "jame", "toge", "luck", "peck", "tass", "calf", "pill", "wore", "wadi", "thur", "parr", "maul", "tzar", "ones", "lees", "dark", "fake", "bast", "zoom", "here", "moro", "wine", "bums", "cows", "jean", "palm", "fume", "plop", "help", "tuba", "leap", "cans", "back", "avid", "lice", "lust", "polo", "dory", "stew", "kate", "rama", "coke", "bled", "mugs", "ajax", "arts", "drug", "pena", "cody", "hole", "sean", "deck", "guts", "kong", "bate", "pitt", "como", "lyle", "siam", "rook", "baby", "jigs", "bret", "bark", "lori", "reba", "sups", "made", "buzz", "gnaw", "alps", "clay", "post", "viol", "dina", "card", "lana", "doff", "yups", "tons", "live", "kids", "pair", "yawl", "name", "oven", "sirs", "gyms", "prig", "down", "leos", "noon", "nibs", "cook", "safe", "cobb", "raja", "awes", "sari", "nerd", "fold", "lots", "pete", "deal", "bias", "zeal", "girl", "rage", "cool", "gout", "whey", "soak", "thaw", "bear", "wing", "nagy", "well", "oink", "sven", "kurt", "etna", "held", "wood", "high", "feta", "twee", "ford", "cave", "knot", "tory", "ibis", "yaks", "vets", "foxy", "sank", "cone", "pius", "tall", "seem", "wool", "flap", "gird", "lore", "coot", "mewl", "sere", "real", "puts", "sell", "nuts", "foil", "lilt", "saga", "heft", "dyed", "goat", "spew", "daze", "frye", "adds", "glen", "tojo", "pixy", "gobi", "stop", "tile", "hiss", "shed", "hahn", "baku", "ahas", "sill", "swap", "also", "carr", "manx", "lime", "debs", "moat", "eked", "bola", "pods", "coon", "lacy", "tube", "minx", "buff", "pres", "clew", "gaff", "flee", "burn", "whom", "cola", "fret", "purl", "wick", "wigs", "donn", "guys", "toni", "oxen", "wite", "vial", "spam", "huts", "vats", "lima", "core", "eula", "thad", "peon", "erie", "oats", "boyd", "cued", "olaf", "tams", "secs", "urey", "wile", "penn", "bred", "rill", "vary", "sues", "mail", "feds", "aves", "code", "beam", "reed", "neil", "hark", "pols", "gris", "gods", "mesa", "test", "coup", "heed", "dora", "hied", "tune", "doze", "pews", "oaks", "bloc", "tips", "maid", "goof", "four", "woof", "silo", "bray", "zest", "kiss", "yong", "file", "hilt", "iris", "tuns", "lily", "ears", "pant", "jury", "taft", "data", "gild", "pick", "kook", "colt", "bohr", "anal", "asps", "babe", "bach", "mash", "biko", "bowl", "huey", "jilt", "goes", "guff", "bend", "nike", "tami", "gosh", "tike", "gees", "urge", "path", "bony", "jude", "lynn", "lois", "teas", "dunn", "elul", "bonn", "moms", "bugs", "slay", "yeah", "loan", "hulk", "lows", "damn", "nell", "jung", "avis", "mane", "waco", "loin", "knob", "tyke", "anna", "hire", "luau", "tidy", "nuns", "pots", "quid", "exec", "hans", "hera", "hush", "shag", "scot", "moan", "wald", "ursa", "lorn", "hunk", "loft", "yore", "alum", "mows", "slog", "emma", "spud", "rice", "worn", "erma", "need", "bags", "lark", "kirk", "pooh", "dyes", "area", "dime", "luvs", "foch", "refs", "cast", "alit", "tugs", "even", "role", "toed", "caph", "nigh", "sony", "bide", "robs", "folk", "daft", "past", "blue", "flaw", "sana", "fits", "barr", "riot", "dots", "lamp", "cock", "fibs", "harp", "tent", "hate", "mali", "togs", "gear", "tues", "bass", "pros", "numb", "emus", "hare", "fate", "wife", "mean", "pink", "dune", "ares", "dine", "oily", "tony", "czar", "spay", "push", "glum", "till", "moth", "glue", "dive", "scad", "pops", "woks", "andy", "leah", "cusp", "hair", "alex", "vibe", "bulb", "boll", "firm", "joys", "tara", "cole", "levy", "owen", "chow", "rump", "jail", "lapp", "beet", "slap", "kith", "more", "maps", "bond", "hick", "opus", "rust", "wist", "shat", "phil", "snow", "lott", "lora", "cary", "mote", "rift", "oust", "klee", "goad", "pith", "heep", "lupe", "ivan", "mimi", "bald", "fuse", "cuts", "lens", "leer", "eyry", "know", "razz", "tare", "pals", "geek", "greg", "teen", "clef", "wags", "weal", "each", "haft", "nova", "waif", "rate", "katy", "yale", "dale", "leas", "axum", "quiz", "pawn", "fend", "capt", "laws", "city", "chad", "coal", "nail", "zaps", "sort", "loci", "less", "spur", "note", "foes", "fags", "gulp", "snap", "bogs", "wrap", "dane", "melt", "ease", "felt", "shea", "calm", "star", "swam", "aery", "year", "plan", "odin", "curd", "mira", "mops", "shit", "davy", "apes", "inky", "hues", "lome", "bits", "vila", "show", "best", "mice", "gins", "next", "roan", "ymir", "mars", "oman", "wild", "heal", "plus", "erin", "rave", "robe", "fast", "hutu", "aver", "jodi", "alms", "yams", "zero", "revs", "wean", "chic", "self", "jeep", "jobs", "waxy", "duel", "seek", "spot", "raps", "pimp", "adan", "slam", "tool", "morn", "futz", "ewes", "errs", "knit", "rung", "kans", "muff", "huhs", "tows", "lest", "meal", "azov", "gnus", "agar", "sips", "sway", "otis", "tone", "tate", "epic", "trio", "tics", "fade", "lear", "owns", "robt", "weds", "five", "lyon", "terr", "arno", "mama", "grey", "disk", "sept", "sire", "bart", "saps", "whoa", "turk", "stow", "pyle", "joni", "zinc", "negs", "task", "leif", "ribs", "malt", "nine", "bunt", "grin", "dona", "nope", "hams", "some", "molt", "smit", "sacs", "joan", "slav", "lady", "base", "heck", "list", "take", "herd", "will", "nubs", "burg", "hugs", "peru", "coif", "zoos", "nick", "idol", "levi", "grub", "roth", "adam", "elma", "tags", "tote", "yaws", "cali", "mete", "lula", "cubs", "prim", "luna", "jolt", "span", "pita", "dodo", "puss", "deer", "term", "dolt", "goon", "gary", "yarn", "aims", "just", "rena", "tine", "cyst", "meld", "loki", "wong", "were", "hung", "maze", "arid", "cars", "wolf", "marx", "faye", "eave", "raga", "flow", "neal", "lone", "anne", "cage", "tied", "tilt", "soto", "opel", "date", "buns", "dorm", "kane", "akin", "ewer", "drab", "thai", "jeer", "grad", "berm", "rods", "saki", "grus", "vast", "late", "lint", "mule", "risk", "labs", "snit", "gala", "find", "spin", "ired", "slot", "oafs", "lies", "mews", "wino", "milk", "bout", "onus", "tram", "jaws", "peas", "cleo", "seat", "gums", "cold", "vang", "dewy", "hood", "rush", "mack", "yuan", "odes", "boos", "jami", "mare", "plot", "swab", "borg", "hays", "form", "mesh", "mani", "fife", "good", "gram", "lion", "myna", "moor", "skin", "posh", "burr", "rime", "done", "ruts", "pays", "stem", "ting", "arty", "slag", "iron", "ayes", "stub", "oral", "gets", "chid", "yens", "snub", "ages", "wide", "bail", "verb", "lamb", "bomb", "army", "yoke", "gels", "tits", "bork", "mils", "nary", "barn", "hype", "odom", "avon", "hewn", "rios", "cams", "tact", "boss", "oleo", "duke", "eris", "gwen", "elms", "deon", "sims", "quit", "nest", "font", "dues", "yeas", "zeta", "bevy", "gent", "torn", "cups", "worm", "baum", "axon", "purr", "vise", "grew", "govs", "meat", "chef", "rest", "lame"]; + +$beginWord = 'hit'; +$endWord = 'cog'; +$wordList = ["hot", "dot", "dog", "lot", "log", "cog"]; + +$s = new Solution(); +$ret = $s->findLadders2($beginWord, $endWord, $wordList); +print_r($ret); + +$res = []; +$visited = ['hit']; +//$ret = $s->dfs($wordMap, $levelMap, $endWord, $beginWord, [], $res, $visited); +//print_r($ret); +//print_r($res); From 8c71c3a4457368ef637f359849f81ce4ce56137b Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Tue, 8 Dec 2020 20:01:51 +0800 Subject: [PATCH 093/192] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E4=B8=80=E7=A7=8D?= =?UTF-8?q?=E9=AB=98=E6=95=88=E7=9A=84=E8=A7=A3=E5=86=B3=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week4/126.word-ladder-ii.php | 53 ++++++++++++++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 2 deletions(-) diff --git a/Week4/126.word-ladder-ii.php b/Week4/126.word-ladder-ii.php index 74433fb8..6fa10146 100644 --- a/Week4/126.word-ladder-ii.php +++ b/Week4/126.word-ladder-ii.php @@ -112,7 +112,7 @@ function findLadders2($beginWord, $endWord, $wordList) // print_r($idWord); // print_r($wordId); - //print_r($edges); + //print_r($edges); $inf = (1 << 20); $cost = array_fill(0, count($idWord), $inf); //cost[i] 代表 i的点 到 beginWord的点 的距离 $res = []; @@ -158,6 +158,55 @@ function transformCheck($word1, $word2) return true; } + /** + * @param String $beginWord + * @param String $endWord + * @param String[] $wordList + * @return String[][] + */ + //防止重复计算,在遍历layer之前,将其中的word在wordlist去重 + // 两个array合并array_merge,返回数组 + function findLadders3($beginWord, $endWord, $wordList) + { + if (!in_array($endWord, $wordList)) { + return []; + } + $wordList = array_flip($wordList); + $layer = [$beginWord => [[$beginWord]]]; + print_r($layer); + $size = strlen($beginWord); + $count = 0; + while (!empty($layer)) { + $new_layer = []; + //从wordList移除已使用的word + foreach (array_keys($layer) as $word) { + unset($wordList[$word]); + } + + foreach (array_keys($layer) as $word) { + //如果找到最后的词 则结束 + if ($word == $endWord) { + return $layer[$word]; + } + + //否则继续搜索邻居单词 + for ($i = 0; $i < $size; $i++) { + $new_word = $word; + for ($ch = ord('a'); $ch <= ord('z'); $ch++) { + $new_word[$i] = chr($ch); + if (array_key_exists($new_word, $wordList)) { //wordList逐渐变小 + foreach ($layer[$word] as $j) { + $new_layer[$new_word][] = array_merge($j, [$new_word]); + } + } + } + } + } + + $layer = $new_layer; + } + return []; + } } @@ -196,7 +245,7 @@ function transformCheck($word1, $word2) $wordList = ["hot", "dot", "dog", "lot", "log", "cog"]; $s = new Solution(); -$ret = $s->findLadders2($beginWord, $endWord, $wordList); +$ret = $s->findLadders3($beginWord, $endWord, $wordList); print_r($ret); $res = []; From 0b28849817314322bed96351ca6ae74d0c8814d5 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Tue, 8 Dec 2020 20:31:14 +0800 Subject: [PATCH 094/192] =?UTF-8?q?=E6=8B=AC=E5=8F=B7=E7=94=9F=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week4/22.generate-parentheses.php | 46 +++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Week4/22.generate-parentheses.php diff --git a/Week4/22.generate-parentheses.php b/Week4/22.generate-parentheses.php new file mode 100644 index 00000000..29ed868a --- /dev/null +++ b/Week4/22.generate-parentheses.php @@ -0,0 +1,46 @@ +dfs($n, 0, 0, '', $res); + return $res; + } + + function dfs($n, $l, $r, $str, &$res) + { + if ($l == $n && $r == $n) { + $res[] = $str; + return; + } + if ($l < $n) { + $this->dfs($n, $l + 1, $r, $str . '(', $res); + } + if ($r < $l) { + $this->dfs($n, $l, $r + 1, $str . ')', $res); + } + } +} + +/** + * 输入:n = 3 + * 输出:[ + * "((()))", + * "(()())", + * "(())()", + * "()(())", + * "()()()" + * ] + */ + +$n = 3; +$s = new Solution(); +$ret = $s->generateParenthesis($n); +print_r($ret); \ No newline at end of file From c300e67e8ae6d9d10cdcb1d66a1819f77820642c Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Tue, 8 Dec 2020 20:57:48 +0800 Subject: [PATCH 095/192] =?UTF-8?q?=E5=9C=A8=E6=AF=8F=E4=B8=AA=E6=A0=91?= =?UTF-8?q?=E8=A1=8C=E4=B8=AD=E6=89=BE=E6=9C=80=E5=A4=A7=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...15.find-largest-value-in-each-tree-row.php | 87 +++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 Week4/515.find-largest-value-in-each-tree-row.php diff --git a/Week4/515.find-largest-value-in-each-tree-row.php b/Week4/515.find-largest-value-in-each-tree-row.php new file mode 100644 index 00000000..89a87d08 --- /dev/null +++ b/Week4/515.find-largest-value-in-each-tree-row.php @@ -0,0 +1,87 @@ +val = $val; + * $this->left = $left; + * $this->right = $right; + * } + * } + */ +class Solution +{ + + /** + * 一DFS O(N) O(N) + * @param TreeNode $root + * @return Integer[] + */ + function largestValues($root) + { + $res = []; + $this->dfs($root, 0, $res); + return array_map(function ($v) { + return max($v); + }, $res); + } + + function dfs($root, $level, &$res) + { + if (!$root) return; + $res[$level][] = $root->val; + $this->dfs($root->left, $level + 1, $res); + $this->dfs($root->right, $level + 1, $res); + } + + /** + * 二BFS O(N) O(N) + * @param TreeNode $root + * @return Integer[] + */ + function largestValues2($root) + { + $res = []; + $queue = new SplQueue(); + $queue->enqueue($root); + $level = 0; + while (!$queue->isEmpty()) { + $size = $queue->count(); + $level++; + for ($i = 0; $i < $size; $i++) { + $node = $queue->dequeue(); + if (!$node) continue; + $res[$level][] = $node->val; + $queue->enqueue($node->left); + $queue->enqueue($node->right); + } + } + return array_map(function ($v) { + return max($v); + }, $res); + } + +} + +/** + * + * 输入: + * + * 1 + * / \ + * 3 2 + * / \ / \ + * 5 3 9 + * + * 输出: [1, 3, 9] + */ + +$root = new BinaryTree([1, 3, 2, 5, 3, 9]); +$s = new Solution(); +$ret = $s->largestValues2($root); +print_r($ret); From 8624da524663f1c84b1e5dd87a1347869d6c90f4 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 10 Dec 2020 05:50:27 +0800 Subject: [PATCH 096/192] =?UTF-8?q?3=E6=95=B0=E4=B9=8B=E5=92=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week1/15.3sum.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Week1/15.3sum.php b/Week1/15.3sum.php index bd56d8e1..06c2c58e 100644 --- a/Week1/15.3sum.php +++ b/Week1/15.3sum.php @@ -15,7 +15,7 @@ function threeSum($nums) $count = count($nums); if ($count < 3) return []; for ($i = 0; $i < $count; $i++) { - if ($nums[$i] > 0) return $ret; + if ($nums[$i] > 0) return $ret; //注意这两个特殊情况 if ($i > 0 && $nums[$i] == $nums[$i - 1]) continue; //注意这个地方一定不要写成 $i-- 死循环 $l = $i + 1; $r = $count - 1; @@ -40,8 +40,11 @@ function threeSum($nums) $in = [-1, 0, 1, 2, -1, -4]; +$in = [-1, 0, 1, 2, -1, -4, -2, -3, 3, 0, 4]; +$in = [0,0,0]; $s = new Solution(); $ret = $s->threeSum($in); +print_r($in); print_r($ret); /* From 196e285c65dc232e2c3862d1c4aa92eee4f2aa33 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 10 Dec 2020 06:12:28 +0800 Subject: [PATCH 097/192] =?UTF-8?q?=E9=9D=A2=E8=AF=95=E9=A2=98=20=E7=AC=AC?= =?UTF-8?q?K=E4=B8=AA=E4=B8=91=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week4/iq1709.get-kth-magic-number-lcci.php | 37 ++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Week4/iq1709.get-kth-magic-number-lcci.php diff --git a/Week4/iq1709.get-kth-magic-number-lcci.php b/Week4/iq1709.get-kth-magic-number-lcci.php new file mode 100644 index 00000000..2c9845c1 --- /dev/null +++ b/Week4/iq1709.get-kth-magic-number-lcci.php @@ -0,0 +1,37 @@ +getKthMagicNumber($k); +print_r($ret); \ No newline at end of file From 02d7999f45789a2d55c6f5496e6e53762d3e1b2c Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sat, 12 Dec 2020 08:37:59 +0800 Subject: [PATCH 098/192] =?UTF-8?q?=E6=9C=80=E5=B0=8F=E5=9F=BA=E5=9B=A0?= =?UTF-8?q?=E5=8F=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week4/433.minimum-genetic-mutation.php | 54 ++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Week4/433.minimum-genetic-mutation.php diff --git a/Week4/433.minimum-genetic-mutation.php b/Week4/433.minimum-genetic-mutation.php new file mode 100644 index 00000000..28d90819 --- /dev/null +++ b/Week4/433.minimum-genetic-mutation.php @@ -0,0 +1,54 @@ +enqueue([$start, $step]); + while (!$queue->isEmpty()) { + $size = $queue->count(); + $step++; + for ($i = 0; $i < $size; $i++) { + list($mid, $level) = $queue->dequeue(); + if ($mid == $end) return $level; + for ($j = 0; $j < strlen($mid); $j++) { + $newMid = $mid; + foreach (['A', 'C', 'G', 'T'] as $char) { + $newMid[$j] = $char; + if (isset($bank[$newMid])) { + $queue->enqueue([$newMid, $level + 1]); + unset($bank[$newMid]); + } + } + } + } + } + return -1; + } +} + +/** + * start: "AAAAACCC" + * end: "AACCCCCC" + * bank: ["AAAACCCC", "AAACCCCC", "AACCCCCC"] + * 返回值: 3 + */ +$start = 'AAAAACCC'; +$end = "AACCCCCC"; +$bank = ["AAAACCCC", "AAACCCCC", "AACCCCCC"]; + +$s = new Solution(); +$ret = $s->minMutation($start, $end, $bank); +print_r($ret); \ No newline at end of file From 84639e6f4ad265ee19e5df42f181b01fcf779f60 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sat, 12 Dec 2020 09:18:10 +0800 Subject: [PATCH 099/192] =?UTF-8?q?=E6=9C=80=E5=B0=8F=E5=9F=BA=E5=9B=A0?= =?UTF-8?q?=E5=8F=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week4/433.minimum-genetic-mutation.php | 44 +++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/Week4/433.minimum-genetic-mutation.php b/Week4/433.minimum-genetic-mutation.php index 28d90819..30c437f3 100644 --- a/Week4/433.minimum-genetic-mutation.php +++ b/Week4/433.minimum-genetic-mutation.php @@ -37,6 +37,48 @@ function minMutation($start, $end, $bank) } return -1; } + + /** + * BFS + * @param String $start + * @param String $end + * @param String[] $bank + * @return Integer + */ + function minMutation2($start, $end, $bank) + { + if (!in_array($end, $bank)) return -1; + $bank = array_flip($bank); + $queue = new SplQueue(); + $step = 0; + $layer = [$start => [[$start]]]; + $queue->enqueue([$layer, $step]); + while (!$queue->isEmpty()) { + $size = $queue->count(); + $step++; + for ($i = 0; $i < $size; $i++) { + list($layer, $level) = $queue->dequeue(); + foreach (array_keys($layer) as $genetic) { + if ($genetic == $end) return $level; + for ($j = 0; $j < strlen($genetic); $j++) { + $newGenetic = $genetic; + foreach (['A', 'C', 'G', 'T'] as $char) { + $newGenetic[$j] = $char; + if (isset($bank[$newGenetic])) { + $newLayer = []; + foreach ($layer[$genetic] as $arrWord) { + $newLayer[$newGenetic][] = array_merge($arrWord, [$newGenetic]); + } + $queue->enqueue([$newLayer, $level + 1]); + unset($bank[$newGenetic]); + } + } + } + } + } + } + return -1; + } } /** @@ -50,5 +92,5 @@ function minMutation($start, $end, $bank) $bank = ["AAAACCCC", "AAACCCCC", "AACCCCCC"]; $s = new Solution(); -$ret = $s->minMutation($start, $end, $bank); +$ret = $s->minMutation2($start, $end, $bank); print_r($ret); \ No newline at end of file From 7460f7447db34a114ba29cb8d2c8f22aceb2c38f Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sat, 12 Dec 2020 11:08:51 +0800 Subject: [PATCH 100/192] =?UTF-8?q?=E6=9C=80=E5=B0=8F=E5=9F=BA=E5=9B=A0?= =?UTF-8?q?=E5=8F=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week4/433.minimum-genetic-mutation.php | 34 +++++++++++++------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/Week4/433.minimum-genetic-mutation.php b/Week4/433.minimum-genetic-mutation.php index 30c437f3..0588041a 100644 --- a/Week4/433.minimum-genetic-mutation.php +++ b/Week4/433.minimum-genetic-mutation.php @@ -54,28 +54,28 @@ function minMutation2($start, $end, $bank) $layer = [$start => [[$start]]]; $queue->enqueue([$layer, $step]); while (!$queue->isEmpty()) { - $size = $queue->count(); - $step++; - for ($i = 0; $i < $size; $i++) { - list($layer, $level) = $queue->dequeue(); - foreach (array_keys($layer) as $genetic) { - if ($genetic == $end) return $level; - for ($j = 0; $j < strlen($genetic); $j++) { - $newGenetic = $genetic; - foreach (['A', 'C', 'G', 'T'] as $char) { - $newGenetic[$j] = $char; - if (isset($bank[$newGenetic])) { - $newLayer = []; - foreach ($layer[$genetic] as $arrWord) { - $newLayer[$newGenetic][] = array_merge($arrWord, [$newGenetic]); - } - $queue->enqueue([$newLayer, $level + 1]); - unset($bank[$newGenetic]); + $newLayer = []; + list($layer, $step) = $queue->dequeue(); + foreach (array_keys($layer) as $genetic) { + unset($bank[$genetic]); + } + foreach (array_keys($layer) as $genetic) { + if ($genetic == $end) return $step; + for ($j = 0; $j < strlen($genetic); $j++) { + $newGenetic = $genetic; + foreach (['A', 'C', 'G', 'T'] as $char) { + $newGenetic[$j] = $char; + if (isset($bank[$newGenetic])) { + foreach ($layer[$genetic] as $arrWord) { + $newLayer[$newGenetic][] = array_merge($arrWord, [$newGenetic]); } } } } } + if (!empty($newLayer)) { + $queue->enqueue([$newLayer, $step + 1]); + } } return -1; } From 6553c548341c0348b7267eaa9c10d54e21bde96c Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sat, 12 Dec 2020 11:25:44 +0800 Subject: [PATCH 101/192] =?UTF-8?q?=E5=8D=95=E8=AF=8D=E6=8E=A5=E9=BE=99II?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week4/126.word-ladder-ii.php | 62 +++++++++++++++++++++++++++++++++--- 1 file changed, 58 insertions(+), 4 deletions(-) diff --git a/Week4/126.word-ladder-ii.php b/Week4/126.word-ladder-ii.php index 6fa10146..93a5ea3d 100644 --- a/Week4/126.word-ladder-ii.php +++ b/Week4/126.word-ladder-ii.php @@ -29,9 +29,10 @@ function findLadders($beginWord, $endWord, $wordList) if ($curWord == $endWord) $canFinish = true; $levelMap[$curWord] = $level; for ($i = 0; $i < strlen($curWord); $i++) { - for ($j = 'a'; $j <= 'z'; $j++) { - $nextWord = $curWord; - $nextWord[$i] = $j; + $nextWord = $curWord; + //for ($j = 'a'; $j <= 'z'; $j++) { //这个写法有问题 卧槽 + for ($j = ord('a'); $j <= ord('z'); $j++) { + $nextWord[$i] = chr($j); if (isset($newWordList[$nextWord])) { if (!isset($wordMap[$curWord])) { $wordMap[$curWord][] = $nextWord; @@ -208,6 +209,54 @@ function findLadders3($beginWord, $endWord, $wordList) return []; } + /** + * @param String $beginWord + * @param String $endWord + * @param String[] $wordList + * @return String[][] + */ + //防止重复计算,在遍历layer之前,将其中的word在wordlist去重 + // 两个array合并array_merge,返回数组 + function findLadders4($beginWord, $endWord, $wordList) + { + if (!in_array($endWord, $wordList)) { + return []; + } + $wordList = array_flip($wordList); + $layer = [$beginWord => [[$beginWord]]]; + $step = 0; + $queue = new SplQueue(); + $queue->enqueue([$layer, $step]); + while (!$queue->isEmpty()) { + $newLayer = []; + list($layer, $step) = $queue->dequeue(); + foreach (array_keys($layer) as $word) { + if ($word == $endWord) return $layer[$word]; + unset($wordList[$word]); + } +// print_r('layer: ' . implode(',', array_keys($layer)) . PHP_EOL); +// print_r('wordList: ' . implode(',', array_keys($wordList)) . PHP_EOL); +// print_r('step: ' . $step . PHP_EOL); +// if($step == 3) break; + foreach (array_keys($layer) as $word) { + for ($j = 0; $j < strlen($word); $j++) { + $newWord = $word; + for ($ch = ord('a'); $ch <= ord('z'); $ch++) { + $newWord[$j] = chr($ch); + if (isset($wordList[$newWord])) { + foreach ($layer[$word] as $arrWord) { + $newLayer[$newWord][] = array_merge($arrWord, [$newWord]); + } + } + } + } + } + if (!empty($newLayer)) { // 注意 为空时不入队 + $queue->enqueue([$newLayer, $step + 1]); + } + } + return []; + } } $wordMap = [ @@ -236,6 +285,11 @@ function findLadders3($beginWord, $endWord, $wordList) 'cog' => 5 ]; +$beginWord = 'hot'; +$endWord = 'dog'; +$wordList = ["hot","dog"]; + + $beginWord = 'sand'; $endWord = 'acne'; $wordList = ["slit", "bunk", "wars", "ping", "viva", "wynn", "wows", "irks", "gang", "pool", "mock", "fort", "heel", "send", "ship", "cols", "alec", "foal", "nabs", "gaze", "giza", "mays", "dogs", "karo", "cums", "jedi", "webb", "lend", "mire", "jose", "catt", "grow", "toss", "magi", "leis", "bead", "kara", "hoof", "than", "ires", "baas", "vein", "kari", "riga", "oars", "gags", "thug", "yawn", "wive", "view", "germ", "flab", "july", "tuck", "rory", "bean", "feed", "rhee", "jeez", "gobs", "lath", "desk", "yoko", "cute", "zeus", "thus", "dims", "link", "dirt", "mara", "disc", "limy", "lewd", "maud", "duly", "elsa", "hart", "rays", "rues", "camp", "lack", "okra", "tome", "math", "plug", "monk", "orly", "friz", "hogs", "yoda", "poop", "tick", "plod", "cloy", "pees", "imps", "lead", "pope", "mall", "frey", "been", "plea", "poll", "male", "teak", "soho", "glob", "bell", "mary", "hail", "scan", "yips", "like", "mull", "kory", "odor", "byte", "kaye", "word", "honk", "asks", "slid", "hopi", "toke", "gore", "flew", "tins", "mown", "oise", "hall", "vega", "sing", "fool", "boat", "bobs", "lain", "soft", "hard", "rots", "sees", "apex", "chan", "told", "woos", "unit", "scow", "gilt", "beef", "jars", "tyre", "imus", "neon", "soap", "dabs", "rein", "ovid", "hose", "husk", "loll", "asia", "cope", "tail", "hazy", "clad", "lash", "sags", "moll", "eddy", "fuel", "lift", "flog", "land", "sigh", "saks", "sail", "hook", "visa", "tier", "maws", "roeg", "gila", "eyes", "noah", "hypo", "tore", "eggs", "rove", "chap", "room", "wait", "lurk", "race", "host", "dada", "lola", "gabs", "sobs", "joel", "keck", "axed", "mead", "gust", "laid", "ends", "oort", "nose", "peer", "kept", "abet", "iran", "mick", "dead", "hags", "tens", "gown", "sick", "odis", "miro", "bill", "fawn", "sumo", "kilt", "huge", "ores", "oran", "flag", "tost", "seth", "sift", "poet", "reds", "pips", "cape", "togo", "wale", "limn", "toll", "ploy", "inns", "snag", "hoes", "jerk", "flux", "fido", "zane", "arab", "gamy", "raze", "lank", "hurt", "rail", "hind", "hoot", "dogy", "away", "pest", "hoed", "pose", "lose", "pole", "alva", "dino", "kind", "clan", "dips", "soup", "veto", "edna", "damp", "gush", "amen", "wits", "pubs", "fuzz", "cash", "pine", "trod", "gunk", "nude", "lost", "rite", "cory", "walt", "mica", "cart", "avow", "wind", "book", "leon", "life", "bang", "draw", "leek", "skis", "dram", "ripe", "mine", "urea", "tiff", "over", "gale", "weir", "defy", "norm", "tull", "whiz", "gill", "ward", "crag", "when", "mill", "firs", "sans", "flue", "reid", "ekes", "jain", "mutt", "hems", "laps", "piss", "pall", "rowe", "prey", "cull", "knew", "size", "wets", "hurl", "wont", "suva", "girt", "prys", "prow", "warn", "naps", "gong", "thru", "livy", "boar", "sade", "amok", "vice", "slat", "emir", "jade", "karl", "loyd", "cerf", "bess", "loss", "rums", "lats", "bode", "subs", "muss", "maim", "kits", "thin", "york", "punt", "gays", "alpo", "aids", "drag", "eras", "mats", "pyre", "clot", "step", "oath", "lout", "wary", "carp", "hums", "tang", "pout", "whip", "fled", "omar", "such", "kano", "jake", "stan", "loop", "fuss", "mini", "byrd", "exit", "fizz", "lire", "emil", "prop", "noes", "awed", "gift", "soli", "sale", "gage", "orin", "slur", "limp", "saar", "arks", "mast", "gnat", "port", "into", "geed", "pave", "awls", "cent", "cunt", "full", "dint", "hank", "mate", "coin", "tars", "scud", "veer", "coax", "bops", "uris", "loom", "shod", "crib", "lids", "drys", "fish", "edit", "dick", "erna", "else", "hahs", "alga", "moho", "wire", "fora", "tums", "ruth", "bets", "duns", "mold", "mush", "swop", "ruby", "bolt", "nave", "kite", "ahem", "brad", "tern", "nips", "whew", "bait", "ooze", "gino", "yuck", "drum", "shoe", "lobe", "dusk", "cult", "paws", "anew", "dado", "nook", "half", "lams", "rich", "cato", "java", "kemp", "vain", "fees", "sham", "auks", "gish", "fire", "elam", "salt", "sour", "loth", "whit", "yogi", "shes", "scam", "yous", "lucy", "inez", "geld", "whig", "thee", "kelp", "loaf", "harm", "tomb", "ever", "airs", "page", "laud", "stun", "paid", "goop", "cobs", "judy", "grab", "doha", "crew", "item", "fogs", "tong", "blip", "vest", "bran", "wend", "bawl", "feel", "jets", "mixt", "tell", "dire", "devi", "milo", "deng", "yews", "weak", "mark", "doug", "fare", "rigs", "poke", "hies", "sian", "suez", "quip", "kens", "lass", "zips", "elva", "brat", "cosy", "teri", "hull", "spun", "russ", "pupa", "weed", "pulp", "main", "grim", "hone", "cord", "barf", "olav", "gaps", "rote", "wilt", "lars", "roll", "balm", "jana", "give", "eire", "faun", "suck", "kegs", "nita", "weer", "tush", "spry", "loge", "nays", "heir", "dope", "roar", "peep", "nags", "ates", "bane", "seas", "sign", "fred", "they", "lien", "kiev", "fops", "said", "lawn", "lind", "miff", "mass", "trig", "sins", "furl", "ruin", "sent", "cray", "maya", "clog", "puns", "silk", "axis", "grog", "jots", "dyer", "mope", "rand", "vend", "keen", "chou", "dose", "rain", "eats", "sped", "maui", "evan", "time", "todd", "skit", "lief", "sops", "outs", "moot", "faze", "biro", "gook", "fill", "oval", "skew", "veil", "born", "slob", "hyde", "twin", "eloy", "beat", "ergs", "sure", "kobe", "eggo", "hens", "jive", "flax", "mons", "dunk", "yest", "begs", "dial", "lodz", "burp", "pile", "much", "dock", "rene", "sago", "racy", "have", "yalu", "glow", "move", "peps", "hods", "kins", "salk", "hand", "cons", "dare", "myra", "sega", "type", "mari", "pelt", "hula", "gulf", "jugs", "flay", "fest", "spat", "toms", "zeno", "taps", "deny", "swag", "afro", "baud", "jabs", "smut", "egos", "lara", "toes", "song", "fray", "luis", "brut", "olen", "mere", "ruff", "slum", "glad", "buds", "silt", "rued", "gelt", "hive", "teem", "ides", "sink", "ands", "wisp", "omen", "lyre", "yuks", "curb", "loam", "darn", "liar", "pugs", "pane", "carl", "sang", "scar", "zeds", "claw", "berg", "hits", "mile", "lite", "khan", "erik", "slug", "loon", "dena", "ruse", "talk", "tusk", "gaol", "tads", "beds", "sock", "howe", "gave", "snob", "ahab", "part", "meir", "jell", "stir", "tels", "spit", "hash", "omit", "jinx", "lyra", "puck", "laue", "beep", "eros", "owed", "cede", "brew", "slue", "mitt", "jest", "lynx", "wads", "gena", "dank", "volt", "gray", "pony", "veld", "bask", "fens", "argo", "work", "taxi", "afar", "boon", "lube", "pass", "lazy", "mist", "blot", "mach", "poky", "rams", "sits", "rend", "dome", "pray", "duck", "hers", "lure", "keep", "gory", "chat", "runt", "jams", "lays", "posy", "bats", "hoff", "rock", "keri", "raul", "yves", "lama", "ramp", "vote", "jody", "pock", "gist", "sass", "iago", "coos", "rank", "lowe", "vows", "koch", "taco", "jinn", "juno", "rape", "band", "aces", "goal", "huck", "lila", "tuft", "swan", "blab", "leda", "gems", "hide", "tack", "porn", "scum", "frat", "plum", "duds", "shad", "arms", "pare", "chin", "gain", "knee", "foot", "line", "dove", "vera", "jays", "fund", "reno", "skid", "boys", "corn", "gwyn", "sash", "weld", "ruiz", "dior", "jess", "leaf", "pars", "cote", "zing", "scat", "nice", "dart", "only", "owls", "hike", "trey", "whys", "ding", "klan", "ross", "barb", "ants", "lean", "dopy", "hock", "tour", "grip", "aldo", "whim", "prom", "rear", "dins", "duff", "dell", "loch", "lava", "sung", "yank", "thar", "curl", "venn", "blow", "pomp", "heat", "trap", "dali", "nets", "seen", "gash", "twig", "dads", "emmy", "rhea", "navy", "haws", "mite", "bows", "alas", "ives", "play", "soon", "doll", "chum", "ajar", "foam", "call", "puke", "kris", "wily", "came", "ales", "reef", "raid", "diet", "prod", "prut", "loot", "soar", "coed", "celt", "seam", "dray", "lump", "jags", "nods", "sole", "kink", "peso", "howl", "cost", "tsar", "uric", "sore", "woes", "sewn", "sake", "cask", "caps", "burl", "tame", "bulk", "neva", "from", "meet", "webs", "spar", "fuck", "buoy", "wept", "west", "dual", "pica", "sold", "seed", "gads", "riff", "neck", "deed", "rudy", "drop", "vale", "flit", "romp", "peak", "jape", "jews", "fain", "dens", "hugo", "elba", "mink", "town", "clam", "feud", "fern", "dung", "newt", "mime", "deem", "inti", "gigs", "sosa", "lope", "lard", "cara", "smug", "lego", "flex", "doth", "paar", "moon", "wren", "tale", "kant", "eels", "muck", "toga", "zens", "lops", "duet", "coil", "gall", "teal", "glib", "muir", "ails", "boer", "them", "rake", "conn", "neat", "frog", "trip", "coma", "must", "mono", "lira", "craw", "sled", "wear", "toby", "reel", "hips", "nate", "pump", "mont", "died", "moss", "lair", "jibe", "oils", "pied", "hobs", "cads", "haze", "muse", "cogs", "figs", "cues", "roes", "whet", "boru", "cozy", "amos", "tans", "news", "hake", "cots", "boas", "tutu", "wavy", "pipe", "typo", "albs", "boom", "dyke", "wail", "woke", "ware", "rita", "fail", "slab", "owes", "jane", "rack", "hell", "lags", "mend", "mask", "hume", "wane", "acne", "team", "holy", "runs", "exes", "dole", "trim", "zola", "trek", "puma", "wacs", "veep", "yaps", "sums", "lush", "tubs", "most", "witt", "bong", "rule", "hear", "awry", "sots", "nils", "bash", "gasp", "inch", "pens", "fies", "juts", "pate", "vine", "zulu", "this", "bare", "veal", "josh", "reek", "ours", "cowl", "club", "farm", "teat", "coat", "dish", "fore", "weft", "exam", "vlad", "floe", "beak", "lane", "ella", "warp", "goth", "ming", "pits", "rent", "tito", "wish", "amps", "says", "hawk", "ways", "punk", "nark", "cagy", "east", "paul", "bose", "solo", "teed", "text", "hews", "snip", "lips", "emit", "orgy", "icon", "tuna", "soul", "kurd", "clod", "calk", "aunt", "bake", "copy", "acid", "duse", "kiln", "spec", "fans", "bani", "irma", "pads", "batu", "logo", "pack", "oder", "atop", "funk", "gide", "bede", "bibs", "taut", "guns", "dana", "puff", "lyme", "flat", "lake", "june", "sets", "gull", "hops", "earn", "clip", "fell", "kama", "seal", "diaz", "cite", "chew", "cuba", "bury", "yard", "bank", "byes", "apia", "cree", "nosh", "judo", "walk", "tape", "taro", "boot", "cods", "lade", "cong", "deft", "slim", "jeri", "rile", "park", "aeon", "fact", "slow", "goff", "cane", "earp", "tart", "does", "acts", "hope", "cant", "buts", "shin", "dude", "ergo", "mode", "gene", "lept", "chen", "beta", "eden", "pang", "saab", "fang", "whir", "cove", "perk", "fads", "rugs", "herb", "putt", "nous", "vane", "corm", "stay", "bids", "vela", "roof", "isms", "sics", "gone", "swum", "wiry", "cram", "rink", "pert", "heap", "sikh", "dais", "cell", "peel", "nuke", "buss", "rasp", "none", "slut", "bent", "dams", "serb", "dork", "bays", "kale", "cora", "wake", "welt", "rind", "trot", "sloe", "pity", "rout", "eves", "fats", "furs", "pogo", "beth", "hued", "edam", "iamb", "glee", "lute", "keel", "airy", "easy", "tire", "rube", "bogy", "sine", "chop", "rood", "elbe", "mike", "garb", "jill", "gaul", "chit", "dons", "bars", "ride", "beck", "toad", "make", "head", "suds", "pike", "snot", "swat", "peed", "same", "gaza", "lent", "gait", "gael", "elks", "hang", "nerf", "rosy", "shut", "glop", "pain", "dion", "deaf", "hero", "doer", "wost", "wage", "wash", "pats", "narc", "ions", "dice", "quay", "vied", "eons", "case", "pour", "urns", "reva", "rags", "aden", "bone", "rang", "aura", "iraq", "toot", "rome", "hals", "megs", "pond", "john", "yeps", "pawl", "warm", "bird", "tint", "jowl", "gibe", "come", "hold", "pail", "wipe", "bike", "rips", "eery", "kent", "hims", "inks", "fink", "mott", "ices", "macy", "serf", "keys", "tarp", "cops", "sods", "feet", "tear", "benz", "buys", "colo", "boil", "sews", "enos", "watt", "pull", "brag", "cork", "save", "mint", "feat", "jamb", "rubs", "roxy", "toys", "nosy", "yowl", "tamp", "lobs", "foul", "doom", "sown", "pigs", "hemp", "fame", "boor", "cube", "tops", "loco", "lads", "eyre", "alta", "aged", "flop", "pram", "lesa", "sawn", "plow", "aral", "load", "lied", "pled", "boob", "bert", "rows", "zits", "rick", "hint", "dido", "fist", "marc", "wuss", "node", "smog", "nora", "shim", "glut", "bale", "perl", "what", "tort", "meek", "brie", "bind", "cake", "psst", "dour", "jove", "tree", "chip", "stud", "thou", "mobs", "sows", "opts", "diva", "perm", "wise", "cuds", "sols", "alan", "mild", "pure", "gail", "wins", "offs", "nile", "yelp", "minn", "tors", "tran", "homy", "sadr", "erse", "nero", "scab", "finn", "mich", "turd", "then", "poem", "noun", "oxus", "brow", "door", "saws", "eben", "wart", "wand", "rosa", "left", "lina", "cabs", "rapt", "olin", "suet", "kalb", "mans", "dawn", "riel", "temp", "chug", "peal", "drew", "null", "hath", "many", "took", "fond", "gate", "sate", "leak", "zany", "vans", "mart", "hess", "home", "long", "dirk", "bile", "lace", "moog", "axes", "zone", "fork", "duct", "rico", "rife", "deep", "tiny", "hugh", "bilk", "waft", "swig", "pans", "with", "kern", "busy", "film", "lulu", "king", "lord", "veda", "tray", "legs", "soot", "ells", "wasp", "hunt", "earl", "ouch", "diem", "yell", "pegs", "blvd", "polk", "soda", "zorn", "liza", "slop", "week", "kill", "rusk", "eric", "sump", "haul", "rims", "crop", "blob", "face", "bins", "read", "care", "pele", "ritz", "beau", "golf", "drip", "dike", "stab", "jibs", "hove", "junk", "hoax", "tats", "fief", "quad", "peat", "ream", "hats", "root", "flak", "grit", "clap", "pugh", "bosh", "lock", "mute", "crow", "iced", "lisa", "bela", "fems", "oxes", "vies", "gybe", "huff", "bull", "cuss", "sunk", "pups", "fobs", "turf", "sect", "atom", "debt", "sane", "writ", "anon", "mayo", "aria", "seer", "thor", "brim", "gawk", "jack", "jazz", "menu", "yolk", "surf", "libs", "lets", "bans", "toil", "open", "aced", "poor", "mess", "wham", "fran", "gina", "dote", "love", "mood", "pale", "reps", "ines", "shot", "alar", "twit", "site", "dill", "yoga", "sear", "vamp", "abel", "lieu", "cuff", "orbs", "rose", "tank", "gape", "guam", "adar", "vole", "your", "dean", "dear", "hebe", "crab", "hump", "mole", "vase", "rode", "dash", "sera", "balk", "lela", "inca", "gaea", "bush", "loud", "pies", "aide", "blew", "mien", "side", "kerr", "ring", "tess", "prep", "rant", "lugs", "hobo", "joke", "odds", "yule", "aida", "true", "pone", "lode", "nona", "weep", "coda", "elmo", "skim", "wink", "bras", "pier", "bung", "pets", "tabs", "ryan", "jock", "body", "sofa", "joey", "zion", "mace", "kick", "vile", "leno", "bali", "fart", "that", "redo", "ills", "jogs", "pent", "drub", "slaw", "tide", "lena", "seep", "gyps", "wave", "amid", "fear", "ties", "flan", "wimp", "kali", "shun", "crap", "sage", "rune", "logs", "cain", "digs", "abut", "obit", "paps", "rids", "fair", "hack", "huns", "road", "caws", "curt", "jute", "fisk", "fowl", "duty", "holt", "miss", "rude", "vito", "baal", "ural", "mann", "mind", "belt", "clem", "last", "musk", "roam", "abed", "days", "bore", "fuze", "fall", "pict", "dump", "dies", "fiat", "vent", "pork", "eyed", "docs", "rive", "spas", "rope", "ariz", "tout", "game", "jump", "blur", "anti", "lisp", "turn", "sand", "food", "moos", "hoop", "saul", "arch", "fury", "rise", "diss", "hubs", "burs", "grid", "ilks", "suns", "flea", "soil", "lung", "want", "nola", "fins", "thud", "kidd", "juan", "heps", "nape", "rash", "burt", "bump", "tots", "brit", "mums", "bole", "shah", "tees", "skip", "limb", "umps", "ache", "arcs", "raft", "halo", "luce", "bahs", "leta", "conk", "duos", "siva", "went", "peek", "sulk", "reap", "free", "dubs", "lang", "toto", "hasp", "ball", "rats", "nair", "myst", "wang", "snug", "nash", "laos", "ante", "opal", "tina", "pore", "bite", "haas", "myth", "yugo", "foci", "dent", "bade", "pear", "mods", "auto", "shop", "etch", "lyly", "curs", "aron", "slew", "tyro", "sack", "wade", "clio", "gyro", "butt", "icky", "char", "itch", "halt", "gals", "yang", "tend", "pact", "bees", "suit", "puny", "hows", "nina", "brno", "oops", "lick", "sons", "kilo", "bust", "nome", "mona", "dull", "join", "hour", "papa", "stag", "bern", "wove", "lull", "slip", "laze", "roil", "alto", "bath", "buck", "alma", "anus", "evil", "dumb", "oreo", "rare", "near", "cure", "isis", "hill", "kyle", "pace", "comb", "nits", "flip", "clop", "mort", "thea", "wall", "kiel", "judd", "coop", "dave", "very", "amie", "blah", "flub", "talc", "bold", "fogy", "idea", "prof", "horn", "shoo", "aped", "pins", "helm", "wees", "beer", "womb", "clue", "alba", "aloe", "fine", "bard", "limo", "shaw", "pint", "swim", "dust", "indy", "hale", "cats", "troy", "wens", "luke", "vern", "deli", "both", "brig", "daub", "sara", "sued", "bier", "noel", "olga", "dupe", "look", "pisa", "knox", "murk", "dame", "matt", "gold", "jame", "toge", "luck", "peck", "tass", "calf", "pill", "wore", "wadi", "thur", "parr", "maul", "tzar", "ones", "lees", "dark", "fake", "bast", "zoom", "here", "moro", "wine", "bums", "cows", "jean", "palm", "fume", "plop", "help", "tuba", "leap", "cans", "back", "avid", "lice", "lust", "polo", "dory", "stew", "kate", "rama", "coke", "bled", "mugs", "ajax", "arts", "drug", "pena", "cody", "hole", "sean", "deck", "guts", "kong", "bate", "pitt", "como", "lyle", "siam", "rook", "baby", "jigs", "bret", "bark", "lori", "reba", "sups", "made", "buzz", "gnaw", "alps", "clay", "post", "viol", "dina", "card", "lana", "doff", "yups", "tons", "live", "kids", "pair", "yawl", "name", "oven", "sirs", "gyms", "prig", "down", "leos", "noon", "nibs", "cook", "safe", "cobb", "raja", "awes", "sari", "nerd", "fold", "lots", "pete", "deal", "bias", "zeal", "girl", "rage", "cool", "gout", "whey", "soak", "thaw", "bear", "wing", "nagy", "well", "oink", "sven", "kurt", "etna", "held", "wood", "high", "feta", "twee", "ford", "cave", "knot", "tory", "ibis", "yaks", "vets", "foxy", "sank", "cone", "pius", "tall", "seem", "wool", "flap", "gird", "lore", "coot", "mewl", "sere", "real", "puts", "sell", "nuts", "foil", "lilt", "saga", "heft", "dyed", "goat", "spew", "daze", "frye", "adds", "glen", "tojo", "pixy", "gobi", "stop", "tile", "hiss", "shed", "hahn", "baku", "ahas", "sill", "swap", "also", "carr", "manx", "lime", "debs", "moat", "eked", "bola", "pods", "coon", "lacy", "tube", "minx", "buff", "pres", "clew", "gaff", "flee", "burn", "whom", "cola", "fret", "purl", "wick", "wigs", "donn", "guys", "toni", "oxen", "wite", "vial", "spam", "huts", "vats", "lima", "core", "eula", "thad", "peon", "erie", "oats", "boyd", "cued", "olaf", "tams", "secs", "urey", "wile", "penn", "bred", "rill", "vary", "sues", "mail", "feds", "aves", "code", "beam", "reed", "neil", "hark", "pols", "gris", "gods", "mesa", "test", "coup", "heed", "dora", "hied", "tune", "doze", "pews", "oaks", "bloc", "tips", "maid", "goof", "four", "woof", "silo", "bray", "zest", "kiss", "yong", "file", "hilt", "iris", "tuns", "lily", "ears", "pant", "jury", "taft", "data", "gild", "pick", "kook", "colt", "bohr", "anal", "asps", "babe", "bach", "mash", "biko", "bowl", "huey", "jilt", "goes", "guff", "bend", "nike", "tami", "gosh", "tike", "gees", "urge", "path", "bony", "jude", "lynn", "lois", "teas", "dunn", "elul", "bonn", "moms", "bugs", "slay", "yeah", "loan", "hulk", "lows", "damn", "nell", "jung", "avis", "mane", "waco", "loin", "knob", "tyke", "anna", "hire", "luau", "tidy", "nuns", "pots", "quid", "exec", "hans", "hera", "hush", "shag", "scot", "moan", "wald", "ursa", "lorn", "hunk", "loft", "yore", "alum", "mows", "slog", "emma", "spud", "rice", "worn", "erma", "need", "bags", "lark", "kirk", "pooh", "dyes", "area", "dime", "luvs", "foch", "refs", "cast", "alit", "tugs", "even", "role", "toed", "caph", "nigh", "sony", "bide", "robs", "folk", "daft", "past", "blue", "flaw", "sana", "fits", "barr", "riot", "dots", "lamp", "cock", "fibs", "harp", "tent", "hate", "mali", "togs", "gear", "tues", "bass", "pros", "numb", "emus", "hare", "fate", "wife", "mean", "pink", "dune", "ares", "dine", "oily", "tony", "czar", "spay", "push", "glum", "till", "moth", "glue", "dive", "scad", "pops", "woks", "andy", "leah", "cusp", "hair", "alex", "vibe", "bulb", "boll", "firm", "joys", "tara", "cole", "levy", "owen", "chow", "rump", "jail", "lapp", "beet", "slap", "kith", "more", "maps", "bond", "hick", "opus", "rust", "wist", "shat", "phil", "snow", "lott", "lora", "cary", "mote", "rift", "oust", "klee", "goad", "pith", "heep", "lupe", "ivan", "mimi", "bald", "fuse", "cuts", "lens", "leer", "eyry", "know", "razz", "tare", "pals", "geek", "greg", "teen", "clef", "wags", "weal", "each", "haft", "nova", "waif", "rate", "katy", "yale", "dale", "leas", "axum", "quiz", "pawn", "fend", "capt", "laws", "city", "chad", "coal", "nail", "zaps", "sort", "loci", "less", "spur", "note", "foes", "fags", "gulp", "snap", "bogs", "wrap", "dane", "melt", "ease", "felt", "shea", "calm", "star", "swam", "aery", "year", "plan", "odin", "curd", "mira", "mops", "shit", "davy", "apes", "inky", "hues", "lome", "bits", "vila", "show", "best", "mice", "gins", "next", "roan", "ymir", "mars", "oman", "wild", "heal", "plus", "erin", "rave", "robe", "fast", "hutu", "aver", "jodi", "alms", "yams", "zero", "revs", "wean", "chic", "self", "jeep", "jobs", "waxy", "duel", "seek", "spot", "raps", "pimp", "adan", "slam", "tool", "morn", "futz", "ewes", "errs", "knit", "rung", "kans", "muff", "huhs", "tows", "lest", "meal", "azov", "gnus", "agar", "sips", "sway", "otis", "tone", "tate", "epic", "trio", "tics", "fade", "lear", "owns", "robt", "weds", "five", "lyon", "terr", "arno", "mama", "grey", "disk", "sept", "sire", "bart", "saps", "whoa", "turk", "stow", "pyle", "joni", "zinc", "negs", "task", "leif", "ribs", "malt", "nine", "bunt", "grin", "dona", "nope", "hams", "some", "molt", "smit", "sacs", "joan", "slav", "lady", "base", "heck", "list", "take", "herd", "will", "nubs", "burg", "hugs", "peru", "coif", "zoos", "nick", "idol", "levi", "grub", "roth", "adam", "elma", "tags", "tote", "yaws", "cali", "mete", "lula", "cubs", "prim", "luna", "jolt", "span", "pita", "dodo", "puss", "deer", "term", "dolt", "goon", "gary", "yarn", "aims", "just", "rena", "tine", "cyst", "meld", "loki", "wong", "were", "hung", "maze", "arid", "cars", "wolf", "marx", "faye", "eave", "raga", "flow", "neal", "lone", "anne", "cage", "tied", "tilt", "soto", "opel", "date", "buns", "dorm", "kane", "akin", "ewer", "drab", "thai", "jeer", "grad", "berm", "rods", "saki", "grus", "vast", "late", "lint", "mule", "risk", "labs", "snit", "gala", "find", "spin", "ired", "slot", "oafs", "lies", "mews", "wino", "milk", "bout", "onus", "tram", "jaws", "peas", "cleo", "seat", "gums", "cold", "vang", "dewy", "hood", "rush", "mack", "yuan", "odes", "boos", "jami", "mare", "plot", "swab", "borg", "hays", "form", "mesh", "mani", "fife", "good", "gram", "lion", "myna", "moor", "skin", "posh", "burr", "rime", "done", "ruts", "pays", "stem", "ting", "arty", "slag", "iron", "ayes", "stub", "oral", "gets", "chid", "yens", "snub", "ages", "wide", "bail", "verb", "lamb", "bomb", "army", "yoke", "gels", "tits", "bork", "mils", "nary", "barn", "hype", "odom", "avon", "hewn", "rios", "cams", "tact", "boss", "oleo", "duke", "eris", "gwen", "elms", "deon", "sims", "quit", "nest", "font", "dues", "yeas", "zeta", "bevy", "gent", "torn", "cups", "worm", "baum", "axon", "purr", "vise", "grew", "govs", "meat", "chef", "rest", "lame"]; @@ -245,7 +299,7 @@ function findLadders3($beginWord, $endWord, $wordList) $wordList = ["hot", "dot", "dog", "lot", "log", "cog"]; $s = new Solution(); -$ret = $s->findLadders3($beginWord, $endWord, $wordList); +$ret = $s->findLadders4($beginWord, $endWord, $wordList); print_r($ret); $res = []; From 55f6c22537ca554c012bcbeb5bc0528b4e4a156d Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sat, 12 Dec 2020 11:25:53 +0800 Subject: [PATCH 102/192] =?UTF-8?q?=E5=8D=95=E8=AF=8D=E6=8E=A5=E9=BE=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week4/127.word-ladder.php | 114 ++++++++++++++++++++++++++------------ 1 file changed, 80 insertions(+), 34 deletions(-) diff --git a/Week4/127.word-ladder.php b/Week4/127.word-ladder.php index 74ce0ac8..74bd9df5 100644 --- a/Week4/127.word-ladder.php +++ b/Week4/127.word-ladder.php @@ -5,7 +5,7 @@ class Solution /** * 一、单向广度优先搜索 - * 这种写法PHP运行起来很慢 不能AC 代码逻辑是正确的 其他语言很快 蛋疼 + * 这种写法PHP运行起来很慢 不能AC 代码逻辑是正确的 多了很多冗余代码 参考最后两种优化代码 * @param String $beginWord * @param String $endWord * @param String[] $wordList @@ -28,7 +28,7 @@ function ladderLength1($beginWord, $endWord, $wordList) $curWord = $queue->dequeue(); for ($j = 0; $j < strlen($curWord); $j++) { $oChar = $curWord[$j]; - for ($k = 'a'; $k <= 'z'; $k++) { + for ($k = 'a'; $k <= 'z'; $k++) { //这种写法有问题 if ($oChar == $k) continue; $nChar = $k; $curWord[$j] = $nChar; @@ -51,6 +51,50 @@ function ladderLength1($beginWord, $endWord, $wordList) return 0; } + /** + * 双向BFS + * 这个相当快 + * @param $beginWord + * @param $endWord + * @param $wordList + * @return int + */ + function ladderLength3($beginWord, $endWord, $wordList) + { + if (!in_array($endWord, $wordList)) return 0; + // 数组中的键和值交换一下 + $newWordList = array_flip($wordList); + $s1[] = $beginWord; + $s2[] = $endWord; + $n = strlen($beginWord); + $step = 0; + while (!empty($s1)) { + $step++; + // 依次双向 BFS 实现,始终使用变量 s1 去运算 + if (count($s1) > count($s2)) { + $temp = $s1; + $s1 = $s2; + $s2 = $temp; + } + $s = []; + foreach ($s1 as $word) { + for ($i = 0; $i < $n; $i++) { + $nextWord = $word; + for ($ch = ord('a'); $ch <= ord('z'); $ch++) { + $nextWord[$i] = chr($ch); + if (in_array($nextWord, $s2)) return $step + 1; + if (isset($newWordList[$nextWord])) { + $s[] = $nextWord; + unset($newWordList[$nextWord]); + } + } + } + } + $s1 = $s; + } + return 0; + } + /** * 一、单向广度优先搜索 * 这个也挺慢的不过相比上一个快不少 能AC @@ -71,9 +115,9 @@ function ladderLength2($beginWord, $endWord, $wordList) list($word, $step) = $queue->dequeue(); if ($word == $endWord) return $step; for ($j = 0; $j < strlen($word); $j++) { - for ($k = 'a'; $k <= 'z'; $k++) { - $nextWord = $word; - $nextWord[$j] = $k; + $nextWord = $word; + for ($k = ord('a'); $k <= ord('z'); $k++) { + $nextWord[$j] = chr($k); if (isset($newWordList[$nextWord])) { $queue->enqueue([$nextWord, $step + 1]); unset($newWordList[$nextWord]); @@ -84,46 +128,48 @@ function ladderLength2($beginWord, $endWord, $wordList) return 0; } + /** - * 双向BFS - * 这个相当快 - * @param $beginWord - * @param $endWord - * @param $wordList - * @return int + * @param String $beginWord + * @param String $endWord + * @param String[] $wordList + * @return String[][] */ + //防止重复计算,在遍历layer之前,将其中的word在wordlist去重 + // 两个array合并array_merge,返回数组 function ladderLength($beginWord, $endWord, $wordList) { - if (!in_array($endWord, $wordList)) return 0; - // 数组中的键和值交换一下 - $newWordList = array_flip($wordList); - $s1[] = $beginWord; - $s2[] = $endWord; - $n = strlen($beginWord); + if (!in_array($endWord, $wordList)) { + return 0; + } + $wordList = array_flip($wordList); + $layer = [$beginWord => [[$beginWord]]]; $step = 0; - while (!empty($s1)) { - $step++; - // 依次双向 BFS 实现,始终使用变量 s1 去运算 - if (count($s1) > count($s2)) { - $temp = $s1; - $s1 = $s2; - $s2 = $temp; + $queue = new SplQueue(); + $queue->enqueue([$layer, $step]); + while (!$queue->isEmpty()) { + $newLayer = []; + list($layer, $step) = $queue->dequeue(); + foreach (array_keys($layer) as $word) { + if ($word == $endWord) return $step + 1; + unset($wordList[$word]); } - $s = []; - foreach ($s1 as $word) { - for ($i = 0; $i < $n; $i++) { - $nextWord = $word; + foreach (array_keys($layer) as $word) { + for ($j = 0; $j < strlen($word); $j++) { + $newWord = $word; for ($ch = ord('a'); $ch <= ord('z'); $ch++) { - $nextWord[$i] = chr($ch); - if (in_array($nextWord, $s2)) return $step + 1; - if (isset($newWordList[$nextWord])) { - $s[] = $nextWord; - unset($newWordList[$nextWord]); + $newWord[$j] = chr($ch); + if (isset($wordList[$newWord])) { + foreach ($layer[$word] as $arrWord) { + $newLayer[$newWord][] = array_merge($arrWord, [$newWord]); + } } } } } - $s1 = $s; + if (!empty($newLayer)) { // 注意 为空时不入队 + $queue->enqueue([$newLayer, $step + 1]); + } } return 0; } From c118489fa5752c214cefcd600137dfdea2722058 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sat, 12 Dec 2020 17:00:14 +0800 Subject: [PATCH 103/192] =?UTF-8?q?=E6=89=AB=E9=9B=B7=E6=B8=B8=E6=88=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week4/529.minesweeper.php | 136 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 136 insertions(+) create mode 100644 Week4/529.minesweeper.php diff --git a/Week4/529.minesweeper.php b/Week4/529.minesweeper.php new file mode 100644 index 00000000..f8980a61 --- /dev/null +++ b/Week4/529.minesweeper.php @@ -0,0 +1,136 @@ +dfs($board, $x, $y); + } + return $board; + } + + function dfs(&$board, $x, $y) + { + $dx = [0, 1, 0, -1, 1, 1, -1, -1]; + $dy = [1, 0, -1, 0, 1, -1, 1, -1]; + $cnt = 0; + for ($i = 0; $i < 8; $i++) { + $nx = $x + $dx[$i]; + $ny = $y + $dy[$i]; + if (!$this->inBoard($board, $nx, $ny)) continue; + if ($board[$nx][$ny] == 'M') { + $cnt++; + } + } + if ($cnt > 0) { + $board[$x][$y] = (string)$cnt; + } else { + $board[$x][$y] = 'B'; + for ($j = 0; $j < 8; $j++) { + $nx = $x + $dx[$j]; + $ny = $y + $dy[$j]; + if (!$this->inBoard($board, $nx, $ny) || $board[$nx][$ny] != 'E') continue; + $this->dfs($board, $nx, $ny); + } + } + } + + function inBoard($board, $x, $y) + { + return $x >= 0 && $y >= 0 && $x < count($board) && $y < count($board[0]); + } + + /** + * 二、BFS O(MN) O(MN) + * @param String[][] $board + * @param Integer[] $click + * @return String[][] + */ + function updateBoard2($board, $click) + { + $x = $click[0]; + $y = $click[1]; + if ($board[$x][$y] == 'M') { + $board[$x][$y] = 'X'; + } else { + $this->bfs($board, $x, $y); + } + return $board; + } + + function bfs(&$board, $x, $y) + { + $visited = []; + for ($i = 0; $i < count($board); $i++) { + for ($j = 0; $j < count($board[0]); $j++) { + $visited[$i][$j] = 0; + } + } + $dx = [0, 1, 0, -1, 1, 1, -1, -1]; + $dy = [1, 0, -1, 0, 1, -1, 1, -1]; + $queue = new SplQueue(); + $queue->enqueue([$x, $y]); + $visited[$x][$y] = 1; + while (!$queue->isEmpty()) { + list($tx, $ty) = $queue->dequeue(); + $cnt = 0; + for ($i = 0; $i < 8; $i++) { + $nx = $tx + $dx[$i]; + $ny = $ty + $dy[$i]; + if (!$this->inBoard($board, $nx, $ny)) continue; + if ($board[$nx][$ny] == 'M') { + $cnt++; + } + } + if ($cnt > 0) { + $board[$tx][$ty] = (string)$cnt; + } else { + $board[$tx][$ty] = 'B'; + for ($i = 0; $i < 8; $i++) { + $nx = $tx + $dx[$i]; + $ny = $ty + $dy[$i]; + if (!$this->inBoard($board, $nx, $ny) || $board[$nx][$ny] != 'E' || $visited[$nx][$ny]) continue; //注意BFS 多了 visited 判断 + $queue->enqueue([$nx, $ny]); + $visited[$nx][$ny] = 1; + } + } + } + } +} + +/** + * 输入: + * [['E', 'E', 'E', 'E', 'E'], + * ['E', 'E', 'M', 'E', 'E'], + * ['E', 'E', 'E', 'E', 'E'], + * ['E', 'E', 'E', 'E', 'E']] + * Click : [3,0] + * 输出: + * [['B', '1', 'E', '1', 'B'], + * ['B', '1', 'M', '1', 'B'], + * ['B', '1', '1', '1', 'B'], + * ['B', 'B', 'B', 'B', 'B']] + */ + +$borad = [ + ['E', 'E', 'E', 'E', 'E'], + ['E', 'E', 'M', 'E', 'E'], + ['E', 'E', 'E', 'E', 'E'], + ['E', 'E', 'E', 'E', 'E'] +]; +$click = [3, 0]; +$s = new Solution(); +$ret = $s->updateBoard2($borad, $click); +print_r($ret); \ No newline at end of file From 3ec0e628b70bd75536f187b00ac4283dc9a93b55 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sun, 13 Dec 2020 09:40:17 +0800 Subject: [PATCH 104/192] =?UTF-8?q?=E4=B9=B0=E5=8D=96=E8=82=A1=E7=A5=A8?= =?UTF-8?q?=E7=9A=84=E6=9C=80=E4=BD=B3=E6=97=B6=E6=9C=BA=20II?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...122.best-time-to-buy-and-sell-stock-ii.php | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Week4/122.best-time-to-buy-and-sell-stock-ii.php diff --git a/Week4/122.best-time-to-buy-and-sell-stock-ii.php b/Week4/122.best-time-to-buy-and-sell-stock-ii.php new file mode 100644 index 00000000..12d32902 --- /dev/null +++ b/Week4/122.best-time-to-buy-and-sell-stock-ii.php @@ -0,0 +1,67 @@ +maxProfit2($prices); +print_r($ret); From d30ec2e46bb5748d66b0194d2e410959fdbb1fd7 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sun, 13 Dec 2020 11:56:19 +0800 Subject: [PATCH 105/192] =?UTF-8?q?=E9=9B=B6=E9=92=B1=E5=85=91=E6=8D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week4/322.coin-change.php | 84 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 Week4/322.coin-change.php diff --git a/Week4/322.coin-change.php b/Week4/322.coin-change.php new file mode 100644 index 00000000..d883ae2a --- /dev/null +++ b/Week4/322.coin-change.php @@ -0,0 +1,84 @@ +dfs($coins, $amount, 0, 0, $res); + return $res == PHP_INT_MAX ? -1 : $res; + } + + function dfs($coins, $amount, $level, $count, &$res) + { + if ($amount == 0) { + $res = min($count, $res); + return; + } + if ($level == count($coins)) return; + for ($k = floor($amount / $coins[$level]); $k >= 0 && ($k + $count) < $res; $k--) { + $this->dfs($coins, $amount - $k * $coins[$level], $level + 1, $k + $count, $res); + } + } + + /** + * 二、动态规划 自下而上 O(Sn) O(S) S金额 n是硬币数量 + * 定义状态 dp[i] 组成面值i所需的最少硬币数量 + * @param Integer[] $coins + * @param Integer $amount + * @return Integer + */ + function coinChange2($coins, $amount) + { + if ($amount == 0) return 0; + $max = $amount + 1; + $dp = array_fill(0, $max, $max); + $dp[0] = 0; + for ($i = 0; $i <= $amount; $i++) { + for ($j = 0; $j < count($coins); $j++) { + if ($i >= $coins[$j]) { + $dp[$i] = min($dp[$i], $dp[$i - $coins[$j]] + 1); + } + } + } + return $dp[$amount] > $amount ? -1 : $dp[$amount]; + } +} + +/** + * 输入:coins = [1, 2, 5], amount = 11 + * 输出:3 + * 解释:11 = 5 + 5 + 1 + * 示例 2: + * + * 输入:coins = [2], amount = 3 + * 输出:-1 + * 示例 3: + * + * 输入:coins = [1], amount = 0 + * 输出:0 + * 示例 4: + * + * 输入:coins = [1], amount = 1 + * 输出:1 + * 示例 5: + * + * 输入:coins = [1], amount = 2 + * 输出:2 + */ + +$coins = [1, 2, 5]; +$amount = 11; +$s = new Solution(); +$ret = $s->coinChange2($coins, $amount); +print_r($ret); \ No newline at end of file From eb83ee54ea1fe2c12bb2879709bb1b40e10517ec Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sun, 13 Dec 2020 20:49:06 +0800 Subject: [PATCH 106/192] =?UTF-8?q?=E6=9F=A0=E6=AA=AC=E6=B0=B4=E6=89=BE?= =?UTF-8?q?=E9=9B=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week4/860.lemonade-change.php | 43 +++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Week4/860.lemonade-change.php diff --git a/Week4/860.lemonade-change.php b/Week4/860.lemonade-change.php new file mode 100644 index 00000000..341375b4 --- /dev/null +++ b/Week4/860.lemonade-change.php @@ -0,0 +1,43 @@ + 0) { + $five--; + $ten++; + } else { + return false; + } + } else { + if ($five > 0 && $ten > 0) { + $five--; + $ten--; + } elseif ($five >= 3) { + $five -= 3; + } else { + return false; + } + } + } + return true; + } +} + +$bills = [5, 5, 5, 10, 20]; +$s = new Solution(); +$ret = $s->lemonadeChange($bills); +print_r($ret); \ No newline at end of file From adc13cae18a6981304a8c0019eb4d6faac7a4d22 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sun, 13 Dec 2020 20:58:24 +0800 Subject: [PATCH 107/192] =?UTF-8?q?=E5=AD=A6=E4=B9=A0=E7=AC=94=E8=AE=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week4/README.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/Week4/README.md b/Week4/README.md index 50de3041..3092f359 100644 --- a/Week4/README.md +++ b/Week4/README.md @@ -1 +1,11 @@ -学习笔记 \ No newline at end of file +学习笔记 + + 贪心算法是一种在每一步选择中都采取在当前状态下最好或最优的选择,从而希望导致结果是全局最好或最优的算法。 + + 贪心算法与动态规划的不同在于它对每个子问题的解决方案都作出选择,不能回退。 + 动态规划则会保存以前的运算结果,并根据以前的结果对当前进行选择,有回退功能。 + + 贪心: 当下做局部最优判断 + 回溯:能够回退 + 动态规划:最优判断 + 回退 + 带最优判断的回溯 => 动态规划 \ No newline at end of file From 0031f16d01095df101189f21b801b93b761aa8fd Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sun, 13 Dec 2020 21:12:38 +0800 Subject: [PATCH 108/192] =?UTF-8?q?=E5=88=86=E5=8F=91=E9=A5=BC=E5=B9=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week4/455.assign-cookies.php | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Week4/455.assign-cookies.php diff --git a/Week4/455.assign-cookies.php b/Week4/455.assign-cookies.php new file mode 100644 index 00000000..8ee53d40 --- /dev/null +++ b/Week4/455.assign-cookies.php @@ -0,0 +1,32 @@ += $g[$gi]) { + $gi++; + } + $si++; + } + return $gi; + } +} + +$g = [1, 2]; +$s = [1, 2, 3]; +$c = new Solution(); +$ret = $c->findContentChildren($g, $s); +print_r($ret); \ No newline at end of file From 55d971627b47c43c2e8f3857fb8b958386da3b20 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sun, 13 Dec 2020 22:28:42 +0800 Subject: [PATCH 109/192] =?UTF-8?q?=E6=A8=A1=E6=8B=9F=E8=A1=8C=E8=B5=B0?= =?UTF-8?q?=E7=9A=84=E6=9C=BA=E5=99=A8=E4=BA=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week4/874.walking-robot-simulation.php | 60 ++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Week4/874.walking-robot-simulation.php diff --git a/Week4/874.walking-robot-simulation.php b/Week4/874.walking-robot-simulation.php new file mode 100644 index 00000000..d206d39b --- /dev/null +++ b/Week4/874.walking-robot-simulation.php @@ -0,0 +1,60 @@ +robotSim($commands, $obstacles); +print_r($ret); \ No newline at end of file From f51c9fd55149ab1ab467f7e756625f991a868f10 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sun, 13 Dec 2020 22:33:45 +0800 Subject: [PATCH 110/192] =?UTF-8?q?=E6=A8=A1=E6=8B=9F=E8=A1=8C=E8=B5=B0?= =?UTF-8?q?=E7=9A=84=E6=9C=BA=E5=99=A8=E4=BA=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week4/874.walking-robot-simulation.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Week4/874.walking-robot-simulation.php b/Week4/874.walking-robot-simulation.php index d206d39b..4c68c1cf 100644 --- a/Week4/874.walking-robot-simulation.php +++ b/Week4/874.walking-robot-simulation.php @@ -38,7 +38,7 @@ function robotSim($commands, $obstacles) if (!isset($hash[$nx][$ny])) { //注意坐标需要移动 $x = $nx; $y = $ny; - $ans = max($ans, $x * $x + $y * $y); + $ans = max($ans, $x * $x + $y ** 2); } } } From 9bc44112baa3e84840a6258aca935da6dfbe08db Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Mon, 14 Dec 2020 11:34:13 +0800 Subject: [PATCH 111/192] =?UTF-8?q?=E6=90=9C=E7=B4=A2=E6=97=8B=E8=BD=AC?= =?UTF-8?q?=E6=8E=92=E5=BA=8F=E6=95=B0=E7=BB=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week4/33.search-in-rotated-sorted-array.php | 52 +++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Week4/33.search-in-rotated-sorted-array.php diff --git a/Week4/33.search-in-rotated-sorted-array.php b/Week4/33.search-in-rotated-sorted-array.php new file mode 100644 index 00000000..1c0c2842 --- /dev/null +++ b/Week4/33.search-in-rotated-sorted-array.php @@ -0,0 +1,52 @@ +> 1); + if ($nums[$mid] == $target) { + return $mid; + } + //左值 <= 中值 左边有序 否则 右边有序 + if ($nums[0] <= $nums[$mid]) { + if ($nums[$l] <= $target && $target < $nums[$mid]) { //这个地方 target 不会等于 mid + $r = $mid - 1; + } else { + $l = $mid + 1; + } + } else { + if ($nums[$mid] < $target && $target <= $nums[$r]) { //这个地方 target 不会等于 mid + $l = $mid + 1; + } else { + $r = $mid - 1; + } + } + } + return -1; + } +} + +/** + * 输入:nums = [4,5,6,7,0,1,2], target = 0 + * 输出:4 + * 输入:nums = [4,5,6,7,0,1,2], target = 3 + * 输出:-1 + */ + +$nums = [4, 5, 6, 7, 0, 1, 2]; +$nums = [4, 5, 6, 7, 0, 1, 2]; +$target = 3; +$target = 0; +$s = new Solution(); +$ret = $s->search($nums, $target); +print_r($ret); \ No newline at end of file From 2d1e0c7fd426fcefe9036981ead8b267a4857652 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Mon, 14 Dec 2020 11:35:21 +0800 Subject: [PATCH 112/192] =?UTF-8?q?=E6=90=9C=E7=B4=A2=E6=97=8B=E8=BD=AC?= =?UTF-8?q?=E6=8E=92=E5=BA=8F=E6=95=B0=E7=BB=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week4/33.search-in-rotated-sorted-array.php | 1 + 1 file changed, 1 insertion(+) diff --git a/Week4/33.search-in-rotated-sorted-array.php b/Week4/33.search-in-rotated-sorted-array.php index 1c0c2842..2a4d9087 100644 --- a/Week4/33.search-in-rotated-sorted-array.php +++ b/Week4/33.search-in-rotated-sorted-array.php @@ -4,6 +4,7 @@ class Solution { /** + * O(LogN) O(1) * @param Integer[] $nums * @param Integer $target * @return Integer From a616975545bd1a7d205d7b464a0ed1984d1ba8f3 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Mon, 14 Dec 2020 12:22:45 +0800 Subject: [PATCH 113/192] =?UTF-8?q?=E5=AF=BB=E6=89=BE=E6=97=8B=E8=BD=AC?= =?UTF-8?q?=E6=8E=92=E5=BA=8F=E6=95=B0=E7=BB=84=E4=B8=AD=E7=9A=84=E6=9C=80?= =?UTF-8?q?=E5=B0=8F=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...3.find-minimum-in-rotated-sorted-array.php | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Week4/153.find-minimum-in-rotated-sorted-array.php diff --git a/Week4/153.find-minimum-in-rotated-sorted-array.php b/Week4/153.find-minimum-in-rotated-sorted-array.php new file mode 100644 index 00000000..63f0e9a5 --- /dev/null +++ b/Week4/153.find-minimum-in-rotated-sorted-array.php @@ -0,0 +1,61 @@ + $nums[0]) return $nums[0]; + while ($l <= $r) { + $mid = $l + (($r - $l) >> 1); + print_r('L:' . $l . '|R:' . $r . '|M:' . $mid . PHP_EOL); + if ($nums[$mid] > $nums[$mid + 1]) return $nums[$mid + 1]; + if ($nums[$mid - 1] > $nums[$mid]) return $nums[$mid]; + if ($nums[0] <= $nums[$mid]) { + $l = $mid + 1; + } else { + $r = $mid - 1; + } + } + return -1; + } + + function findMin2($nums) + { + $left = 0; + $right = count($nums) - 1; + while ($left < $right) { + $mid = floor($left + ($right - $left) / 2); + if ($nums[$mid] > $nums[$right]) { + $left = $mid + 1; + } else { + $right = $mid; + } + } + return $nums[$left]; + } + +} + +/** + * 输入:nums = [3,4,5,1,2] + * 输出:1 + * 输入:nums = [4,5,6,7,0,1,2] + * 输出:0 + * 输入:nums = [1] + * 输出:1 + */ + +$nums = [1]; +$nums = [11, 13, 15, 17]; +$nums = [4, 5, 6, 7, 1, 2]; +$s = new Solution(); +$ret = $s->findMin2($nums); +print_r($ret); \ No newline at end of file From 22daeb85fd51f027b04517e4e64e2b07ed73686f Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Mon, 14 Dec 2020 17:11:59 +0800 Subject: [PATCH 114/192] =?UTF-8?q?X=E7=9A=84=E5=B9=B3=E6=96=B9=E6=A0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week4/69.sqrtx.php | 57 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Week4/69.sqrtx.php diff --git a/Week4/69.sqrtx.php b/Week4/69.sqrtx.php new file mode 100644 index 00000000..e4ef6a4f --- /dev/null +++ b/Week4/69.sqrtx.php @@ -0,0 +1,57 @@ + Xi+1 = 0.5 * (Xi + C / Xi) + * @param Integer $x + * @return Integer + */ + function mySqrt($x) + { + if ($x == 0) return 0; + $x0 = $c = $x; + while (true) { + $xi = 0.5 * ($x0 + $c / $x0); + if (abs($xi - $x0) < 1e-5) { //php科学计数法 + break; + } + $x0 = $xi; + } + return (int)$x0; + } + + /** + * 二、二分查找 O(LogX) O(1) + * @param Integer $x + * @return Integer + */ + function mySqrt2($x) + { + $l = 0; $r = $x; $ans = -1; + while($l <= $r) { + $mid = $l + (($r - $l) >> 1); + if($mid ** 2 <= $x) { + $ans = $mid; + $l = $mid + 1; + }else{ + $r = $mid - 1; + } + } + return $ans; + } +} + +/** + * 输入: 8 + * 输出: 2 + * 说明: 8 的平方根是 2.82842..., + * 由于返回类型是整数,小数部分将被舍去。 + */ + +$x = 8; +$s = new Solution(); +$ret = $s->mySqrt2($x); +print_r($ret); \ No newline at end of file From 4808f5a2c73ff85a3c3d22a3f0b490d3c3973a89 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Mon, 14 Dec 2020 17:59:43 +0800 Subject: [PATCH 115/192] =?UTF-8?q?=E6=9C=89=E6=95=88=E7=9A=84=E5=AE=8C?= =?UTF-8?q?=E5=85=A8=E5=B9=B3=E6=96=B9=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week4/367.valid-perfect-square.php | 50 ++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Week4/367.valid-perfect-square.php diff --git a/Week4/367.valid-perfect-square.php b/Week4/367.valid-perfect-square.php new file mode 100644 index 00000000..0777da86 --- /dev/null +++ b/Week4/367.valid-perfect-square.php @@ -0,0 +1,50 @@ +> 1); + while ($x ** 2 > $num) { + //print_r('x0:' . $x . PHP_EOL); + $x = (($x + ($num / $x)) >> 1); + //print_r('x1:' . $x . PHP_EOL); + } + return $x ** 2 == $num; + } + + /** + * 二、二分查找 O(LogN) O(1) + * @param Integer $num + * @return Boolean + */ + function isPerfectSquare2($num) + { + if ($num < 2) return true; + $l = 2; + $r = ($num >> 1); + while ($l <= $r) { + $mid = $l + (($r - $l) >> 1); + if ($mid ** 2 == $num) return true; + if ($mid ** 2 > $num) { + $r = $mid - 1; + } else { + $l = $mid + 1; + } + } + return false; + } + +} + +$num = 14; +$s = new Solution(); +$ret = $s->isPerfectSquare2($num); +var_dump($ret); \ No newline at end of file From 7ef917c9630e74a20865876099bb43b9fd7e76d5 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Mon, 14 Dec 2020 18:01:17 +0800 Subject: [PATCH 116/192] =?UTF-8?q?=E6=9C=89=E6=95=88=E5=AE=8C=E5=85=A8?= =?UTF-8?q?=E5=B9=B3=E6=96=B9=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week4/367.valid-perfect-square.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Week4/367.valid-perfect-square.php b/Week4/367.valid-perfect-square.php index 0777da86..37149953 100644 --- a/Week4/367.valid-perfect-square.php +++ b/Week4/367.valid-perfect-square.php @@ -14,7 +14,7 @@ function isPerfectSquare($num) $x = ($num >> 1); while ($x ** 2 > $num) { //print_r('x0:' . $x . PHP_EOL); - $x = (($x + ($num / $x)) >> 1); + $x = (($x + ($num / $x)) >> 1); //注意这个地方需要向下取整 //print_r('x1:' . $x . PHP_EOL); } return $x ** 2 == $num; From fd8c4199d0675784844ffa6bb1cec035057041ff Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Mon, 14 Dec 2020 18:37:47 +0800 Subject: [PATCH 117/192] =?UTF-8?q?=E6=90=9C=E7=B4=A2=E4=BA=8C=E7=BB=B4?= =?UTF-8?q?=E7=9F=A9=E9=98=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week4/74.search-a-2d-matrix.php | 42 +++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Week4/74.search-a-2d-matrix.php diff --git a/Week4/74.search-a-2d-matrix.php b/Week4/74.search-a-2d-matrix.php new file mode 100644 index 00000000..18fe5593 --- /dev/null +++ b/Week4/74.search-a-2d-matrix.php @@ -0,0 +1,42 @@ +> 1); + $x = floor($mid / $col); //注意这个地方不是除以2不能位运算 + $y = $mid % $col; + $midVal = $matrix[$x][$y]; //关键在这 坐标变换 其他都是标准二分查找 + //print_r('col:' . $col . '|row:' . $row . '|L:' . $l . '|R:' . $r . '|m:' . $mid . '|x:' . $x . '|y:' . $y . '|v:' . $midVal . PHP_EOL); + if ($midVal == $target) return true; + if ($midVal > $target) { + $r = $mid - 1; + } else { + $l = $mid + 1; + } + } + return false; + } +} + +$matrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50]]; +$target = 31; +$matrix = [[1], [3]]; +$target = 3; +$s = new Solution(); +$ret = $s->searchMatrix($matrix, $target); +var_dump($ret); From 11480a54055d993be1031b70e910102700a0c400 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Tue, 15 Dec 2020 07:16:04 +0800 Subject: [PATCH 118/192] =?UTF-8?q?=E8=B7=B3=E8=B7=83=E6=B8=B8=E6=88=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week4/55.jump-game.php | 54 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Week4/55.jump-game.php diff --git a/Week4/55.jump-game.php b/Week4/55.jump-game.php new file mode 100644 index 00000000..406258a2 --- /dev/null +++ b/Week4/55.jump-game.php @@ -0,0 +1,54 @@ += count($nums) - 1) { + return true; + } + } + } + return false; + } + + /** + * @param Integer[] $nums + * @return Boolean + */ + function canJump2($nums) + { + $m = 0; + foreach ($nums as $k => $v) { + if ($k > $m) return false; + $m = max($m, $k + $v); + } + return true; + } +} + +/** + * 输入: [2,3,1,1,4] + * 输出: true + * 解释: 我们可以先跳 1 步,从位置 0 到达 位置 1, 然后再从位置 1 跳 3 步到达最后一个位置。 + * 输入: [3,2,1,0,4] + * 输出: false + * 解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。 + */ +$nums = [2, 3, 1, 1, 4]; +$nums = [3, 2, 1, 0, 4]; +$s = new Solution(); +$ret = $s->canJump($nums); +var_dump($ret); From c9a7f8fbd31b9fe3e7d3f424fbdefb8b231e1692 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Tue, 15 Dec 2020 07:59:42 +0800 Subject: [PATCH 119/192] =?UTF-8?q?=E8=B7=B3=E8=B7=83=E6=B8=B8=E6=88=8FII?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week4/45.jump-game-ii.php | 59 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Week4/45.jump-game-ii.php diff --git a/Week4/45.jump-game-ii.php b/Week4/45.jump-game-ii.php new file mode 100644 index 00000000..abc5f92b --- /dev/null +++ b/Week4/45.jump-game-ii.php @@ -0,0 +1,59 @@ + 0) { + for ($i = 0; $i < $n; $i++) { + if ($i + $nums[$i] >= $position) { + $step++; + $position = $i; + break; + } + } + } + return $step; + } + + /** + * 一、贪心 正向查找 O(N) O(1) + * @param Integer[] $nums + * @return Integer + */ + function jump($nums) + { + $n = count($nums); + $masPosition = 0; + $end = 0; //最大位置下标 + $step = 0; + for ($i = 0; $i < $n - 1; $i++) { //注意不访问最后一个位置 + $masPosition = max($masPosition, $i + $nums[$i]); + if ($i == $end) { + $step++; + $end = $masPosition; + } + } + return $step; + } +} + +/** + * 输入: [2,3,1,1,4] + * 输出: 2 + * 解释: 跳到最后一个位置的最小跳跃数是 2。 + * 从下标为 0 跳到下标为 1 的位置,跳1步,然后跳3步到达数组的最后一个位置。 + */ +$nums = [2, 3, 1, 1, 4]; +$s = new Solution(); +$ret = $s->jump($nums); +print_r($ret); \ No newline at end of file From 9da2b59131bf14b13859bf3fc2f8d4cd7b8098c7 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Tue, 15 Dec 2020 09:52:50 +0800 Subject: [PATCH 120/192] =?UTF-8?q?4=E6=95=B0=E4=B9=8B=E5=92=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week5/4sum.php | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Week5/4sum.php diff --git a/Week5/4sum.php b/Week5/4sum.php new file mode 100644 index 00000000..e350c0c9 --- /dev/null +++ b/Week5/4sum.php @@ -0,0 +1,52 @@ + 0 && $nums[$i] == $nums[$i-1]) continue; //防重复剪枝 + if ($nums[$i] + $nums[$i + 1] + $nums[$i + 2] + $nums[$i + 3] > $target) break; //最小值比target大无解 剪枝 + for ($j = $i + 1; $j < $n - 2; $j++) { + if($j > $i + 1 && $nums[$j] == $nums[$j - 1]) continue; //防重复剪枝 注意这个地方是 $i + 1; + if ($nums[$i] + $nums[$j] + $nums[$n - 2] + $nums[$n - 1] < $target) continue; //最大值比targe小 此层无解剪枝 + $l = $j + 1; + $r = $n - 1; + while ($l < $r) { + $sum = $nums[$i] + $nums[$j] + $nums[$l] + $nums[$r]; + if ($sum > $target) { + $r--; + } elseif ($sum == $target) { + $res[] = [$nums[$i], $nums[$j], $nums[$l], $nums[$r]]; + $l++; + $r--; + while ($l < $r && $nums[$l] == $nums[$l - 1]) $l++; + while ($l < $r && $nums[$r] == $nums[$r + 1]) $r--; + } else { + $l++; + } + + } + } + } + return $res; + } +} + +$nums = [0, 0, 0, 0]; +$target = 0; +$nums = [1, 0, -1, 0, -2, 2]; +$target = 0; +$s = new Solution(); +$ret = $s->fourSum($nums, $target); +print_r($ret); \ No newline at end of file From 0f95e440c9782876f11a712d2f6be7fe09101082 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 17 Dec 2020 07:19:18 +0800 Subject: [PATCH 121/192] =?UTF-8?q?=E5=8D=95=E8=AF=8D=E8=A7=84=E5=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week5/290.word-pattern.php | 58 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Week5/290.word-pattern.php diff --git a/Week5/290.word-pattern.php b/Week5/290.word-pattern.php new file mode 100644 index 00000000..03195adb --- /dev/null +++ b/Week5/290.word-pattern.php @@ -0,0 +1,58 @@ += $lenStr) return false; //str 少于 ch 的情况 + $j = $k; + while ($j < $lenStr && $s[$j] != ' ') $j++; + $str = substr($s, $k, $j - $k); + $ch = $pattern[$i]; + print_r('k:' . $k . '|j:' . $j . '|ch:' . $ch . '|str:' . $str . PHP_EOL); + if (isset($str2ch[$str]) && $str2ch[$str] != $ch) return false; + if (isset($ch2str[$ch]) && $ch2str[$ch] != $str) return false; + $str2ch[$str] = $ch; + $ch2str[$ch] = $str; + $k = $j + 1; + } + //print_r($str2ch); + //print_r($ch2str); + return $k >= $lenStr; //str 多于 ch 的情况 + } +} + +/** + * 输入: pattern = "abba", str = "dog cat cat dog" + * 输出: true + * 输入:pattern = "abba", str = "dog cat cat fish" + * 输出: false + * 输入: pattern = "aaaa", str = "dog cat cat dog" + * 输出: false + * 输入: pattern = "abba", str = "dog dog dog dog" + * 输出: false + */ + +$p = 'abba'; +$str = 'dog cat cat dog'; +$str = 'dog cat cat fish'; +$p = 'aaa'; +$str = 'aa aa aa aa'; +$p = 'he'; +$str = 'unit'; +$s = new Solution(); +$ret = $s->wordPattern($p, $str); +var_dump($ret); \ No newline at end of file From c1fb1c6e008e73fd393d735784d0bf282002f32c Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Fri, 18 Dec 2020 13:32:21 +0800 Subject: [PATCH 122/192] =?UTF-8?q?=E9=9B=B6=E9=92=B1=E5=85=91=E6=8D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week5/518.coin-change-2.php | 83 +++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 Week5/518.coin-change-2.php diff --git a/Week5/518.coin-change-2.php b/Week5/518.coin-change-2.php new file mode 100644 index 00000000..7c8dc658 --- /dev/null +++ b/Week5/518.coin-change-2.php @@ -0,0 +1,83 @@ += 0) $dp[$t--][0] = 1; + for ($i = 1; $i <= $amount; $i++) { + for ($j = 1; $j <= $k; $j++) { + if ($i >= $coins[$j - 1]) { + $dp[$j][$i] = $dp[$j - 1][$i] + $dp[$j][$i - $coins[$j - 1]]; + } else { + $dp[$j][$i] = $dp[$j - 1][$i]; + } + } + } + return $dp[$k][$amount]; + } + + /** + * 此时的子问题是,对于硬币从0到k,我们必须使用第k个硬币的时候,当前金额的组合数。 + * 因此状态数组DP[i]表示的是对于第k个硬币能凑的组合数 + * 状态转移方程如下 + * DP[[i] = DP[i] + DP[i-k] + * 我们这里定义的子问题是,必须选择第k个硬币时,凑成金额i的方案。如果内外循环交换了,我们的子问题就变了,那就是对于金额i, 我们选择硬币的方案。 + * @param $amount + * @param $coins + * @return mixed + */ + function change2($amount, $coins) + { + $k = count($coins); + $dp = array_fill(0, $amount + 1, 0); + $dp[0] = 1; +// for ($j = 0; $j < $k; $j++) { +// for ($i = 1; $i <= $amount; $i++) { +// if ($i < $coins[$j]) continue; +// $dp[$i] += $dp[$i - $coins[$j]]; +// } +// } + foreach ($coins as $coin) { + //优化循环,减少数组索引访问 + for($i = $coin;$i <= $amount;$i++) { + $dp[$i] += $dp[$i - $coin]; + } + } + print_r($dp); + return $dp[$amount]; + } +} + +/** + *输入: amount = 5, coins = [1, 2, 5] + * 输出: 4 + * 解释: 有四种方式可以凑成总金额: + * 5=5 + * 5=2+2+1 + * 5=2+1+1+1 + * 5=1+1+1+1+1 + */ + +$amount = 6; +$coins = [2, 3, 5]; +$s = new Solution(); +$ret = $s->change2($amount, $coins); +print_r($ret); \ No newline at end of file From 36c5842ac73cadf5e5af1d8a69b1711f4c719c0f Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Fri, 18 Dec 2020 15:01:24 +0800 Subject: [PATCH 123/192] =?UTF-8?q?=E9=9B=B6=E9=92=B1=E5=85=91=E6=8D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week5/518.coin-change-2.php | 43 +++++++++++++++++++++++++++++++------ 1 file changed, 37 insertions(+), 6 deletions(-) diff --git a/Week5/518.coin-change-2.php b/Week5/518.coin-change-2.php index 7c8dc658..4419a5d1 100644 --- a/Week5/518.coin-change-2.php +++ b/Week5/518.coin-change-2.php @@ -57,13 +57,42 @@ function change2($amount, $coins) // } foreach ($coins as $coin) { //优化循环,减少数组索引访问 - for($i = $coin;$i <= $amount;$i++) { - $dp[$i] += $dp[$i - $coin]; - } + for ($i = $coin; $i <= $amount; $i++) { + $dp[$i] += $dp[$i - $coin]; + } } print_r($dp); return $dp[$amount]; } + + /** + * https://leetcode-cn.com/problems/coin-change-2/solution/c-bei-bao-wen-ti-by-yizhe-shi/ + * @param $amount + * @param $coins + * @return array + */ + function change3($amount, $coins) + { + $res = []; + $k = count($coins); + $this->dfs($coins, $amount, 0, [], $res); + return $res; + } + + function dfs($coins, $amount, $level, $path, &$res) + { + if ($amount == 0) { + $res[] = $path; + return; + } + for ($i = 0; $i < count($coins); $i++) { + if ($coins[$i] <= $amount) { + array_push($path, $coins[$i]); + $this->dfs($coins, $amount - $coins[$i], $level + 1, $path, $res); + array_pop($path); + } + } + } } /** @@ -76,8 +105,10 @@ function change2($amount, $coins) * 5=1+1+1+1+1 */ -$amount = 6; -$coins = [2, 3, 5]; +$amount = 4; +$coins = [1, 2, 3]; +$amount = 5; +$coins = [1, 2, 5]; $s = new Solution(); -$ret = $s->change2($amount, $coins); +$ret = $s->change3($amount, $coins); print_r($ret); \ No newline at end of file From b9caaebf34e56a8dee11724347ea32b1c7f572bc Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Fri, 18 Dec 2020 15:42:11 +0800 Subject: [PATCH 124/192] =?UTF-8?q?=E4=B8=8D=E5=90=8C=E8=B7=AF=E5=BE=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week5/62.unique-paths.php | 86 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 Week5/62.unique-paths.php diff --git a/Week5/62.unique-paths.php b/Week5/62.unique-paths.php new file mode 100644 index 00000000..68844e65 --- /dev/null +++ b/Week5/62.unique-paths.php @@ -0,0 +1,86 @@ += 0) $dp[$t--][0] = 1; + $t = $n; + while ($t >= 0) $dp[0][$t--] = 1; + for ($i = 1; $i < $m; $i++) { + for ($j = 1; $j < $n; $j++) { + $dp[$i][$j] = $dp[$i - 1][$j] + $dp[$i][$j - 1]; + } + } + return $dp[$m - 1][$n - 1]; + } + + /** + * 动态规划 O(mn) O(min(m,n)); + * @param Integer $m + * @param Integer $n + * @return Integer + */ + function uniquePaths2($m, $n) + { + $dp = array_fill(0, $n, 1); + for ($i = 1; $i < $m; $i++) { + for ($j = 1; $j < $n; $j++) { + $dp[$j] += $dp[$j - 1]; + } + } + print_r($dp); + return $dp[$n - 1]; + } + + /** + * 组合数学 O(mn) O(min(m,n)); + * 我们要想到达终点,需要往下走n-1步,往右走m-1步,总共需要走n+m-2步。他无论往右走还是往下走他的总的步数是不会变的。 + * 也就相当于总共要走n+m-2步,往右走m-1步总共有多少种走法,很明显这就是一个排列组合问题 + * @param Integer $m + * @param Integer $n + * @return Integer + */ + function uniquePaths3($m, $n) + { + $N = $m + $n - 2; + $ans = 1; + for ($i = 1; $i < $m; $i++) { + $ans *= ($N - ($m - 1) + $i) / $i; + } + return $ans; + } + +} + +/** + * 输入:m = 3, n = 2 + * 输出:3 + * 解释: + * 从左上角开始,总共有 3 条路径可以到达右下角。 + * 1. 向右 -> 向右 -> 向下 + * 2. 向右 -> 向下 -> 向右 + * 3. 向下 -> 向右 -> 向右 + * + * 输入:m = 7, n = 3 + * 输出:28 + * + * 输入:m = 3, n = 3 + * 输出:6 + */ + +$m = 7; +$n = 3; +$s = new Solution(); +$ret = $s->uniquePaths3($m, $n); +print_r($ret); \ No newline at end of file From cfdaf2c7a0d577efec6a44eb7c5426705e81aabb Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Fri, 18 Dec 2020 16:07:33 +0800 Subject: [PATCH 125/192] =?UTF-8?q?=E6=89=BE=E4=B8=8D=E5=90=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week5/389.find-the-difference.php | 76 +++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 Week5/389.find-the-difference.php diff --git a/Week5/389.find-the-difference.php b/Week5/389.find-the-difference.php new file mode 100644 index 00000000..6c394a6e --- /dev/null +++ b/Week5/389.find-the-difference.php @@ -0,0 +1,76 @@ +findTheDifference2($s1, $t); +print_r($ret); From ef6d0f1f17afb6c62597f8fa03a1186b2c12c7e0 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sat, 19 Dec 2020 22:40:49 +0800 Subject: [PATCH 126/192] =?UTF-8?q?=E5=92=8C=E4=B8=BAk=E7=9A=84=E5=AD=90?= =?UTF-8?q?=E6=95=B0=E7=BB=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week5/560.subarray-sum-equals-k.php | 67 +++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Week5/560.subarray-sum-equals-k.php diff --git a/Week5/560.subarray-sum-equals-k.php b/Week5/560.subarray-sum-equals-k.php new file mode 100644 index 00000000..6d27e62a --- /dev/null +++ b/Week5/560.subarray-sum-equals-k.php @@ -0,0 +1,67 @@ += 0; $j--) { + $sum += $nums[$j]; + if ($sum == $k) { + $count++; + } + } + } + return $count; + } + + /** + * 一 前缀和 + 哈希 O(n) O(n) + * @param Integer[] $nums + * @param Integer $k + * @return Integer + */ + function subarraySum2($nums, $k) + { + $count = 0; + $hash = []; + $sum = 0; + for ($i = 0; $i < count($nums); $i++) { + $sum += $nums[$i]; + if ($sum == $k) { + $count++; + } + if (isset($hash[$sum - $k])) $count += $hash[$sum - $k]; + if (!isset($hash[$sum])) { + $hash[$sum] = 1; + } else { + $hash[$sum]++; + } + } + return $count; + } +} + +/** + * 输入:nums = [1,1,1], k = 2 + * 输出: 2 , [1,1] 与 [1,1] 为两种不同的情况。 + * 输入: nums = [0,0,0,0,0,0,0,0,0,0] , k = 0 + * 输出: 55 + */ + +$nums = [1, 1, 1]; +$k = 2; +$nums = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; +$k = 0; +$s = new Solution(); +$ret = $s->subarraySum2($nums, $k); +print_r($ret); From d6094f1f1c317aa9cb60b31940b86bbee7152c7c Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sat, 19 Dec 2020 22:51:50 +0800 Subject: [PATCH 127/192] =?UTF-8?q?=E5=92=8C=E4=B8=BAk=E7=9A=84=E5=AD=90?= =?UTF-8?q?=E6=95=B0=E7=BB=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week5/560.subarray-sum-equals-k.php | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/Week5/560.subarray-sum-equals-k.php b/Week5/560.subarray-sum-equals-k.php index 6d27e62a..a1a68765 100644 --- a/Week5/560.subarray-sum-equals-k.php +++ b/Week5/560.subarray-sum-equals-k.php @@ -49,6 +49,32 @@ function subarraySum2($nums, $k) } return $count; } + + /** + * 一 前缀和 + 哈希 O(n) O(n) + * @param Integer[] $nums + * @param Integer $k + * @return Integer + */ + function subarraySum3($nums, $k) + { + $count = 0; + $hash = [0 => 1]; + $sum = 0; + for ($i = 0; $i < count($nums); $i++) { + $sum += $nums[$i]; + if (isset($hash[$sum - $k])) { + $count += $hash[$sum - $k]; + } + if (!isset($hash[$sum])) { + $hash[$sum] = 1; + } else { + $hash[$sum]++; + } + } + print_r($hash); + return $count; + } } /** @@ -63,5 +89,5 @@ function subarraySum2($nums, $k) $nums = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; $k = 0; $s = new Solution(); -$ret = $s->subarraySum2($nums, $k); +$ret = $s->subarraySum3($nums, $k); print_r($ret); From 5f7824ae264f17280adc1ff37d96408e753ab4fb Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Tue, 22 Dec 2020 13:57:18 +0800 Subject: [PATCH 128/192] =?UTF-8?q?=E6=9C=80=E5=A4=A7=E5=AD=90=E5=BA=8F?= =?UTF-8?q?=E5=92=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week6/53.maximum-subarray.php | 75 +++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 Week6/53.maximum-subarray.php diff --git a/Week6/53.maximum-subarray.php b/Week6/53.maximum-subarray.php new file mode 100644 index 00000000..1cd32fd2 --- /dev/null +++ b/Week6/53.maximum-subarray.php @@ -0,0 +1,75 @@ +get($nums, 0, count($nums) - 1)[2]; + } + + /** + * 求a序列任意区间[l,r]最大子序列和 + * @param $a + * @param $l + * @param $r + * lSum 表示 [l, r][l,r] 内以 ll 为左端点的最大子段和 + * rSum 表示 [l, r][l,r] 内以 rr 为右端点的最大子段和 + * mSum 表示 [l, r][l,r] 内的最大子段和 + * iSum 表示 [l, r][l,r] 的区间和 + * return [lSum rSum mSum iSum] + */ + function get($a, $l, $r) + { + if ($l == $r) { + return [$a[$l], $a[$l], $a[$l], $a[$l]]; + } + $mid = $l + (($r - $l) >> 1); + $lSub = $this->get($a, $l, $mid); + $rSub = $this->get($a, $mid + 1, $r); + return $this->pushUp($lSub, $rSub); + } + + function pushUp($lSub, $rSub) + { + return [ + max($lSub[0],$lSub[3] + $rSub[0]), + max($rSub[1],$rSub[3] + $lSub[1]), + max($lSub[2],$rSub[2],$lSub[1] + $rSub[0]), + $lSub[3] + $rSub[3], + ]; + } + +} + +/** + * 输入: [-2,1,-3,4,-1,2,1,-5,4] + * 输出: 6 + * 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。 + */ + +$nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]; //6 +$nums = [1,2,-1,-2,2,1,-2,1]; //3 +$s = new Solution(); +$ret = $s->maxSubArray2($nums); +print_r($ret); \ No newline at end of file From 65d526264a6111bf881a7b8e08a6cc2b5cc69ca4 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Tue, 22 Dec 2020 14:31:12 +0800 Subject: [PATCH 129/192] =?UTF-8?q?=E6=9C=80=E9=95=BF=E5=85=AC=E5=85=B1?= =?UTF-8?q?=E5=AD=90=E5=BA=8F=E5=88=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week6/1143.longest-common-subsequence.php | 67 +++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Week6/1143.longest-common-subsequence.php diff --git a/Week6/1143.longest-common-subsequence.php b/Week6/1143.longest-common-subsequence.php new file mode 100644 index 00000000..6bee35a0 --- /dev/null +++ b/Week6/1143.longest-common-subsequence.php @@ -0,0 +1,67 @@ +dp($text1, $text2, $n1 - 1, $n2 - 1); + } + + function dp($s1, $s2, $i, $j) + { + if ($i == -1 || $j == -1) return 0; + if ($s1[$i] == $s2[$j]) { + return 1 + $this->dp($s1, $s2, $i - 1, $j - 1); + } else { + return max($this->dp($s1, $s2, $i - 1, $j), $this->dp($s1, $s2, $i, $j - 1)); + } + } +} + +/** + * 输入:text1 = "abcde", text2 = "ace" + * 输出:3 + * 解释:最长公共子序列是 "ace",它的长度为 3。 + * + * 输入:text1 = "abc", text2 = "abc" + * 输出:3 + * 解释:最长公共子序列是 "abc",它的长度为 3。 + * + * 输入:text1 = "abc", text2 = "def" + * 输出:0 + * 解释:两个字符串没有公共子序列,返回 0。 + */ + +$text1 = 'abcde'; +$text2 = 'ace'; +$s = new Solution(); +$ret = $s->longestCommonSubsequence2($text1, $text2); +print_r($ret); \ No newline at end of file From 06fee0c75a96ad87f0aa41f8caf13d198629054c Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Tue, 22 Dec 2020 15:23:21 +0800 Subject: [PATCH 130/192] =?UTF-8?q?=E6=9C=80=E9=95=BF=E9=80=92=E5=A2=9E?= =?UTF-8?q?=E5=AD=90=E5=BA=8F=E5=88=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week6/300.longest-increasing-subsequence.php | 72 ++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 Week6/300.longest-increasing-subsequence.php diff --git a/Week6/300.longest-increasing-subsequence.php b/Week6/300.longest-increasing-subsequence.php new file mode 100644 index 00000000..bd898b7d --- /dev/null +++ b/Week6/300.longest-increasing-subsequence.php @@ -0,0 +1,72 @@ + $tail[$end]) { + $tail[++$end] = $nums[$i]; + } else { + $l = 0; + $r = $end; + $pos = 0; + while ($l <= $r) { + $mid = $l + (($r - $l) >> 1); + if ($nums[$i] > $tail[$mid]) { //查找右边界 + $l = $mid + 1; + print_r('L:' . $l . '|R:' . $r . '|m:' . $mid . PHP_EOL); + $pos = $l; + } else { + $r = $mid - 1; + } + } + $tail[$pos] = $nums[$i]; + } + print_r($tail); + } + return $end + 1; + } +} + +/** + *输入:nums = [10,9,2,5,3,7,101,18] + * 输出:4 + * 解释:最长递增子序列是 [2,3,7,101],因此长度为 4 。 + */ +$nums = [10, 9, 2, 5, 3, 7, 101, 18]; +$s = new Solution(); +$ret = $s->lengthOfLIS2($nums); +print_r($ret); \ No newline at end of file From 688cabafb2bd2e41260e1f37e51a38c7292929ea Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Tue, 22 Dec 2020 15:25:20 +0800 Subject: [PATCH 131/192] =?UTF-8?q?=E6=9C=80=E9=95=BF=E5=85=AC=E5=85=B1?= =?UTF-8?q?=E5=AD=90=E5=BA=8F=E5=88=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week6/1143.longest-common-subsequence.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Week6/1143.longest-common-subsequence.php b/Week6/1143.longest-common-subsequence.php index 6bee35a0..d93364dd 100644 --- a/Week6/1143.longest-common-subsequence.php +++ b/Week6/1143.longest-common-subsequence.php @@ -28,6 +28,12 @@ function longestCommonSubsequence($text1, $text2) return $dp[$n1][$n2]; } + /** + * 递归写法 超时 + * @param $text1 + * @param $text2 + * @return int|mixed + */ function longestCommonSubsequence2($text1, $text2) { $n1 = strlen($text1); From f4a533335f3a113e47bfc1b96ca54fe774162c7a Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Tue, 22 Dec 2020 15:52:28 +0800 Subject: [PATCH 132/192] =?UTF-8?q?=E5=AD=98=E5=9C=A8=E9=87=8D=E5=A4=8D?= =?UTF-8?q?=E5=85=83=E7=B4=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week5/217.contains-duplicate.php | 44 ++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Week5/217.contains-duplicate.php diff --git a/Week5/217.contains-duplicate.php b/Week5/217.contains-duplicate.php new file mode 100644 index 00000000..c48c96b5 --- /dev/null +++ b/Week5/217.contains-duplicate.php @@ -0,0 +1,44 @@ + 1) return true; + } + } + return false; + } +} + +$nums = [1, 2, 3, 1]; +$nums = [1, 2, 3, 4]; +$nums = [0]; +//$ret = (new Solution())->containsDuplicate($nums); +$ret = (new Solution())->containsDuplicate2($nums); +var_dump($ret); \ No newline at end of file From 6d83ae1159c4b3d0d4e0aaf5b5b469321ba66b4a Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Tue, 22 Dec 2020 16:57:23 +0800 Subject: [PATCH 133/192] =?UTF-8?q?=E4=B8=8D=E5=90=8C=E8=B7=AF=E5=BE=84II?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week5/63.unique-paths-ii.php | 87 ++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 Week5/63.unique-paths-ii.php diff --git a/Week5/63.unique-paths-ii.php b/Week5/63.unique-paths-ii.php new file mode 100644 index 00000000..bd10fa08 --- /dev/null +++ b/Week5/63.unique-paths-ii.php @@ -0,0 +1,87 @@ + 0 && $obstacleGrid[$i][$j - 1] == 0) + $dp[$j] += $dp[$j - 1]; + } + } + return $dp[$col - 1]; + } +} + +/** + *输入:obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]] + * 输出:2 + * 解释: + * 3x3 网格的正中间有一个障碍物。 + * 从左上角到右下角一共有 2 条不同的路径: + * 1. 向右 -> 向右 -> 向下 -> 向下 + * 2. 向下 -> 向下 -> 向右 -> 向右 + */ + +$obstacleGrid = [[0, 0, 1], [0, 0, 0], [1, 0, 0]]; +$obstacleGrid = [[0, 1], [0, 0]]; //1 +$obstacleGrid = [[0, 0, 0], [0, 1, 0], [0, 0, 0]]; //2 +$obstacleGrid = [[0,1]]; //0 +$s = new Solution(); +$ret = $s->uniquePathsWithObstacles2($obstacleGrid); +print_r($ret); \ No newline at end of file From 97e1e6426861dbffb51b7e4293ce685e96159e23 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Tue, 22 Dec 2020 17:29:49 +0800 Subject: [PATCH 134/192] =?UTF-8?q?=E5=8F=AA=E5=87=BA=E7=8E=B0=E4=B8=80?= =?UTF-8?q?=E6=AC=A1=E7=9A=84=E6=95=B0=E7=BB=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week5/136.single-number.php | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Week5/136.single-number.php diff --git a/Week5/136.single-number.php b/Week5/136.single-number.php new file mode 100644 index 00000000..8a102aff --- /dev/null +++ b/Week5/136.single-number.php @@ -0,0 +1,22 @@ +singleNumber($nums); +print_r($ret); \ No newline at end of file From 2dcab8f1d4c59f7b54c46273379d4fd99bc4e473 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 23 Dec 2020 15:49:56 +0800 Subject: [PATCH 135/192] =?UTF-8?q?=E4=B8=89=E8=A7=92=E5=BD=A2=E6=9C=80?= =?UTF-8?q?=E5=B0=8F=E8=B7=AF=E5=BE=84=E5=92=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week6/120.triangle.php | 73 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 Week6/120.triangle.php diff --git a/Week6/120.triangle.php b/Week6/120.triangle.php new file mode 100644 index 00000000..6bba3eba --- /dev/null +++ b/Week6/120.triangle.php @@ -0,0 +1,73 @@ += 0; $i--) { + for ($j = 0; $j <= $i; $j++) { + if ($i == $n - 1) { + $dp[$i][$j] = $triangle[$i][$j]; + } else { + $dp[$i][$j] = $triangle[$i][$j] + min($dp[$i + 1][$j], $dp[$i + 1][$j + 1]); + } + } + } + return $dp[0][0]; + } + + /** + * 二、动态规划 O(N^2) O(N) + * dp[j] 表示从点 (i, j) 到底边的最小路径和。 + * dp[j] = min(dp[j], dp[j+1]) + triangle[i][j] + * @param Integer[][] $triangle + * @return Integer + */ + function minimumTotal2($triangle) + { + $n = count($triangle); + $dp = []; + for ($i = $n - 1; $i >= 0; $i--) { + for ($j = 0; $j <= $i; $j++) { + if ($i == $n - 1) { + $dp[$j] = $triangle[$i][$j]; + } else { + $dp[$j] = $triangle[$i][$j] + min($dp[$j], $dp[$j + 1]); + } + } + } + return $dp[0]; + } +} + +/** + *例如,给定三角形: + * + * [ + * [2], + * [3,4], + * [6,5,7], + * [4,1,8,3] + * ] + * 自顶向下的最小路径和为11(即,2+3+5+1= 11)。 + */ + +$triangle = + [ + [2], + [3, 4], + [6, 5, 7], + [4, 1, 8, 3] + ]; +$ret = (new Solution())->minimumTotal2($triangle); +print_r($ret); \ No newline at end of file From 7f22a8e50f441c00e44bad9467b3cf48f034f7a4 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 23 Dec 2020 16:34:59 +0800 Subject: [PATCH 136/192] =?UTF-8?q?=E4=B9=98=E7=A7=AF=E6=9C=80=E5=A4=A7?= =?UTF-8?q?=E5=AD=90=E5=8C=BA=E9=97=B4=E6=95=B0=E7=BB=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week6/152.maximum-product-subarray.php | 30 ++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Week6/152.maximum-product-subarray.php diff --git a/Week6/152.maximum-product-subarray.php b/Week6/152.maximum-product-subarray.php new file mode 100644 index 00000000..f8ebaadd --- /dev/null +++ b/Week6/152.maximum-product-subarray.php @@ -0,0 +1,30 @@ +maxProduct($nums); +print_r($ret); From a05d2cc0da5c2ec70610e545f7d89023a3784a63 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 23 Dec 2020 16:46:47 +0800 Subject: [PATCH 137/192] =?UTF-8?q?=E9=9B=B6=E9=92=B1=E5=85=91=E6=8D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week4/322.coin-change.php | 1 + 1 file changed, 1 insertion(+) diff --git a/Week4/322.coin-change.php b/Week4/322.coin-change.php index d883ae2a..da91d1c3 100644 --- a/Week4/322.coin-change.php +++ b/Week4/322.coin-change.php @@ -34,6 +34,7 @@ function dfs($coins, $amount, $level, $count, &$res) /** * 二、动态规划 自下而上 O(Sn) O(S) S金额 n是硬币数量 * 定义状态 dp[i] 组成面值i所需的最少硬币数量 + * $dp[i] = min(dp[i - ci]) + 1; * @param Integer[] $coins * @param Integer $amount * @return Integer From 5f6ad48a050300b391ad9c5abd96a39a9d33b0af Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 23 Dec 2020 17:07:24 +0800 Subject: [PATCH 138/192] =?UTF-8?q?=E6=89=93=E5=AE=B6=E5=8A=AB=E8=88=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week6/198.house-robber.php | 52 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Week6/198.house-robber.php diff --git a/Week6/198.house-robber.php b/Week6/198.house-robber.php new file mode 100644 index 00000000..3d46e1ab --- /dev/null +++ b/Week6/198.house-robber.php @@ -0,0 +1,52 @@ +rob2($nums); +print_r($ret); From cf1c74934954eed884ef084b087e11f298718a9d Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 23 Dec 2020 17:46:12 +0800 Subject: [PATCH 139/192] =?UTF-8?q?=E6=89=93=E5=AE=B6=E5=8A=AB=E8=88=8DII?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week6/213.house-robber-ii.php | 37 +++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Week6/213.house-robber-ii.php diff --git a/Week6/213.house-robber-ii.php b/Week6/213.house-robber-ii.php new file mode 100644 index 00000000..ca6e95b5 --- /dev/null +++ b/Week6/213.house-robber-ii.php @@ -0,0 +1,37 @@ +robRange($nums, 0, $n - 2), $this->robRange($nums, 1, $n - 1)); + } + + function robRange($nums, $start, $end) + { + $n = count($nums); + if ($n == 0) return 0; + if ($n == 1) return $nums[$start]; + if ($n == 2) return max($nums[$start], $nums[$start + 1]); + $dp0 = $nums[$start]; + $dp1 = max($nums[$start], $nums[$start + 1]); + for ($i = $start + 2; $i <= $end; $i++) { + $temp = $dp1; + $dp1 = max($dp1, $nums[$i] + $dp0); + $dp0 = $temp; + } + return $dp1; + } +} + +$nums = [2, 3, 2]; //3 +$nums = [1, 3, 1, 3, 100]; //103 +$ret = (new Solution())->rob($nums); +print_r($ret); \ No newline at end of file From 615526e34a43b03151adc0d7ca5dd71fc24b54c3 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 23 Dec 2020 17:59:44 +0800 Subject: [PATCH 140/192] =?UTF-8?q?=E6=89=93=E5=AE=B6=E5=8A=AB=E8=88=8DIII?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week6/337.house-robber-iii.php | 54 ++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Week6/337.house-robber-iii.php diff --git a/Week6/337.house-robber-iii.php b/Week6/337.house-robber-iii.php new file mode 100644 index 00000000..5fa808a3 --- /dev/null +++ b/Week6/337.house-robber-iii.php @@ -0,0 +1,54 @@ +val = $value; } + * } + */ +class Solution +{ + + /** + * @param TreeNode $root + * @return Integer + */ + function rob($root) + { + return max($this->dfs($root)); + } + + function dfs($root) + { + if (!$root) return [0, 0]; + $left = $this->dfs($root->left); + $right = $this->dfs($root->right); + $rob = $root->val + $left[0] + $right[0]; //抢当前根节点 + $noRob = max($left[0], $left[1]) + max($right[0], $right[1]); //不抢当前根节点 + return [$noRob, $rob]; + } +} + +/** + * 3 + * / \ + * 2 3 + * \ \ + * 3 1 + */ +$nums = [3, 2, 3, null, 3, null, 1]; //7 +/** + * 3 + * / \ + * 4 5 + * / \ \ + * 1 3 1 + */ +$nums = [3, 4, 5, 1, 3, null, 1]; //9 +$root = new BinaryTree($nums); +$ret = (new Solution())->rob($root); +print_r($ret); \ No newline at end of file From 91384f57d51704bff29d2db2e44a6bb634214196 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 23 Dec 2020 21:04:20 +0800 Subject: [PATCH 141/192] =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2=E4=B8=AD?= =?UTF-8?q?=E7=9A=84=E7=AC=AC=E4=B8=80=E4=B8=AA=E5=94=AF=E4=B8=80=E5=AD=97?= =?UTF-8?q?=E7=AC=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...387.first-unique-character-in-a-string.php | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Week6/387.first-unique-character-in-a-string.php diff --git a/Week6/387.first-unique-character-in-a-string.php b/Week6/387.first-unique-character-in-a-string.php new file mode 100644 index 00000000..9da2092d --- /dev/null +++ b/Week6/387.first-unique-character-in-a-string.php @@ -0,0 +1,37 @@ +firstUniqChar($s); +print_r($ret); From dd64ae777266fefc6d9daaa4e0b5f451a4eece3f Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 23 Dec 2020 22:01:47 +0800 Subject: [PATCH 142/192] =?UTF-8?q?=E5=92=8C=E4=B8=BAk=E7=9A=84=E5=AD=90?= =?UTF-8?q?=E5=8C=BA=E9=97=B4=E6=95=B0=E7=BB=84=20=E5=A2=9E=E5=8A=A0mytest?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week5/560.subarray-sum-equals-k.php | 44 ++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/Week5/560.subarray-sum-equals-k.php b/Week5/560.subarray-sum-equals-k.php index a1a68765..0c6e3b95 100644 --- a/Week5/560.subarray-sum-equals-k.php +++ b/Week5/560.subarray-sum-equals-k.php @@ -75,6 +75,45 @@ function subarraySum3($nums, $k) print_r($hash); return $count; } + + function test($nums, $k) + { + $res = []; + $this->dfs($nums, $k, 0, [], $res); + return $res; + } + + function dfs($nums, $k, $level, $list, &$res) + { + if ($k == 0) { + $res[] = $list; + } + for ($i = $level; $i < count($nums); $i++) { + array_push($list, $nums[$i]); + $this->dfs($nums, $k - $nums[$i], $i + 1, $list, $res); + array_pop($list); + } + } + + function test2($nums, $k) + { + $res = []; + $this->dfs2($nums, $k, 0, [], $res); + return $res; + } + + function dfs2($nums, $k, $level, $list, &$res) + { + if ($level == count($nums)) return; + if ($k == 0) { + $res[] = $list; + return; + } + $this->dfs($nums, $k, $level + 1, $list, $res); + array_push($list, $nums[$level]); + $this->dfs($nums, $k - $nums[$level], $level + 1, $list, $res); + array_pop($list); + } } /** @@ -88,6 +127,9 @@ function subarraySum3($nums, $k) $k = 2; $nums = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; $k = 0; +$nums = [1, 2, 3, 3]; +$k = 6; $s = new Solution(); -$ret = $s->subarraySum3($nums, $k); +//$ret = $s->subarraySum3($nums, $k); +$ret = $s->test2($nums, $k); print_r($ret); From 931cd4a9c696d1a5da83239296480ccf02ecd3fe Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 23 Dec 2020 22:22:45 +0800 Subject: [PATCH 143/192] =?UTF-8?q?=E5=8A=A8=E6=80=81=E8=A7=84=E5=88=92?= =?UTF-8?q?=E6=B1=82=E8=A7=A3=E6=9C=80=E5=A4=A7=E8=BF=9E=E7=BB=AD=E5=AD=90?= =?UTF-8?q?=E6=95=B0=E7=BB=84=E5=92=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week6/53.maximum-subarray.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Week6/53.maximum-subarray.php b/Week6/53.maximum-subarray.php index 1cd32fd2..cc1bc7a9 100644 --- a/Week6/53.maximum-subarray.php +++ b/Week6/53.maximum-subarray.php @@ -4,7 +4,7 @@ class Solution { /** - * 一、动态规划 O(N) O(1) + * 一、动态规划求解最大连续子数组和 O(N) O(1) * @param Integer[] $nums * @return Integer */ From 6c5bd309a50419ef007bbc9c80d98fea185af980 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 23 Dec 2020 23:41:10 +0800 Subject: [PATCH 144/192] =?UTF-8?q?=E4=B9=B0=E5=8D=96=E8=82=A1=E7=A5=A8?= =?UTF-8?q?=E7=9A=84=E6=9C=80=E4=BD=B3=E6=97=B6=E6=9C=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week6/121.best-time-to-buy-and-sell-stock.php | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Week6/121.best-time-to-buy-and-sell-stock.php diff --git a/Week6/121.best-time-to-buy-and-sell-stock.php b/Week6/121.best-time-to-buy-and-sell-stock.php new file mode 100644 index 00000000..9827862c --- /dev/null +++ b/Week6/121.best-time-to-buy-and-sell-stock.php @@ -0,0 +1,67 @@ + $maxProfit) { + $maxProfit = $prices[$i] - $minPrice; + } + } + return $maxProfit; + } + + /** + * 二、动态规划 O(N) O(1) + * 这是一个最大连续子数组和的问题, 区间和可以转换成求差的问题,求差问题,也可以转换成区间和的问题。求原数组中两元素的最大差等价于求差数组的最大子序和。 + * 最大连续子数组和可以使用动态规划求解, dp[i] 表示以 i 为结尾的最大连续子数组和,递推公式为: + * dp[i] = max(diff[i], dp[i-1] + diff[i]) + * + * 由于数组中数据是不连续的,在本题中【求导弱化为求差】,即 f'[0] = (f[1] - f[0]) / 1 - 0 = f[1] - f[0], + * 对【原数组】进行求导之后得到的是【差数组】。 求【原数组】的【最大差】的问题转换为求【差数组】的【最大子序和】问题。 + * 差分就是离散形式下的微分 微分就是导数 + * @param Integer[] $prices + * @return Integer + */ + function maxProfit2($prices) + { + $diff = []; + for ($i = 0; $i < count($prices) - 1; $i++) { + $diff[$i] = $prices[$i + 1] - $prices[$i]; + } + //print_r($diff); + //$dp[0] = max(0, $diff[0]); + $preSum = max(0, $diff[0]); + $maxProfit = max(0, $diff[0]); + for ($j = 1; $j < count($diff); $j++) { + //$dp[$j] = max($dp[$j - 1] + $diff[$j], $diff[$j]); + $preSum = max($preSum + $diff[$j], $diff[$j]); + $maxProfit = max($preSum, $maxProfit); + //$maxProfit = max($dp[$j], $maxProfit); + } + //print_r($dp); + return $maxProfit; + } +} + +/** + * 输入: [7,1,5,3,6,4] + * 输出: 5 + * 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。 + * 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。 + */ + +$prices = [7, 1, 5, 3, 6, 4]; +$ret = (new Solution())->maxProfit2($prices); +print_r($ret); \ No newline at end of file From 2b3c8d13842ebaac237ffe1fac2e2be216ab3a37 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 24 Dec 2020 18:07:29 +0800 Subject: [PATCH 145/192] =?UTF-8?q?=E6=9C=80=E5=B0=8F=E8=B7=AF=E5=BE=84?= =?UTF-8?q?=E5=92=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week6/64.minimum-path-sum.php | 36 +++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Week6/64.minimum-path-sum.php diff --git a/Week6/64.minimum-path-sum.php b/Week6/64.minimum-path-sum.php new file mode 100644 index 00000000..81b5a90f --- /dev/null +++ b/Week6/64.minimum-path-sum.php @@ -0,0 +1,36 @@ +minPathSum($grid); +print_r($ret); \ No newline at end of file From c66f30fe5a3683ef11b06989aefe0e77d899a417 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 24 Dec 2020 21:17:04 +0800 Subject: [PATCH 146/192] =?UTF-8?q?=E4=B9=B0=E5=8D=96=E8=82=A1=E7=A5=A8?= =?UTF-8?q?=E7=9A=84=E6=9C=80=E4=BD=B3=E6=97=B6=E6=9C=BAIII?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...23.best-time-to-buy-and-sell-stock-iii.php | 101 ++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 Week6/123.best-time-to-buy-and-sell-stock-iii.php diff --git a/Week6/123.best-time-to-buy-and-sell-stock-iii.php b/Week6/123.best-time-to-buy-and-sell-stock-iii.php new file mode 100644 index 00000000..cc880fae --- /dev/null +++ b/Week6/123.best-time-to-buy-and-sell-stock-iii.php @@ -0,0 +1,101 @@ +maxProfit($prices); +print_r($ret); \ No newline at end of file From ebf5faa6661b47eb82546d8429620924a33e9871 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Fri, 25 Dec 2020 23:56:06 +0800 Subject: [PATCH 147/192] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E6=89=93=E5=8D=B0?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Lib/BinaryTree.php | 108 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 107 insertions(+), 1 deletion(-) diff --git a/Lib/BinaryTree.php b/Lib/BinaryTree.php index 927600db..2522d2e8 100644 --- a/Lib/BinaryTree.php +++ b/Lib/BinaryTree.php @@ -31,8 +31,114 @@ function createTree($arrTree, $i) } return $root; } + + function printTree($root) + { + //计算树高 + $treeHeight = $this->treeHeight($root); + + //层序遍历计算原坐标 + $queue = new SplQueue(); + $queue->push($root); + $level = 0; + $arrTree = []; + while (!$queue->isEmpty()) { + $size = $queue->count(); + if ($level == $treeHeight) break; + for ($i = 0; $i < $size; $i++) { + $node = $queue->dequeue(); + $arrTree[$level][$i] = !$node ? 'nul' : $node->val; + if (!$node) continue; //这个地方需要使用continue 而不是判断左节点是否为空 因为左节点为kong 也要记录的 + $queue->enqueue($node->left); + $queue->enqueue($node->right); + } + $level++; + } + //print_r($arrTree); + + //计算新坐标 + $dp = []; + for ($i = $treeHeight - 1; $i >= 0; $i--) { + for ($j = 0; $j < count($arrTree[$i]); $j++) { + if ($i == count($arrTree) - 1) { + $dp[$i][$j] = [$i, 2 * $j]; + } else { + $dp[$i][$j] = [$i, ($dp[$i + 1][2 * $j][1] + $dp[$i + 1][2 * $j + 1][1]) / 2]; + } + } + } + //print_r($dp); + + //初始化打印数组 + $row = $treeHeight; + $col = 2 ** $treeHeight; + $tmp = array_fill(0, $col, ' '); + $arrPrint = array_fill(0, $row, $tmp); + + //填充打印数组 + $width = 2; + for ($i = 0; $i < count($arrTree); $i++) { + for ($j = 0; $j < count($arrTree[$i]); $j++) { + $x = $dp[$i][$j][0]; + $y = $dp[$i][$j][1]; + $arrPrint[$x][$y] = $arrTree[$i][$j]; + $width = max($width, strlen($arrTree[$i][$j])); + } + } + //print_r($arrPrint); + + //执行打印 + //print_r($width); + for ($i = 0; $i < count($arrPrint); $i++) { + for ($j = 0; $j < count($arrPrint[$i]); $j++) { + echo sprintf("%' " . $width . "s", $arrPrint[$i][$j]); + } + echo PHP_EOL; + } + } + + function treeHeight($root) + { + if (!$root) return 0; + return max($this->treeHeight($root->left), $this->treeHeight($root->right)) + 1; + } + } +/** + * 1 + * / \ + *2 3 + * 1 + * / \ + * 2 3 + * / \ / \ + *4 5 6 7 + * 1 + * / \ + * 2 3 + * / \ / \ + * 4 5 6 7 + * / \ / \ / \ / \ + *8 9 10 11 12 13 14 15 + * + * 1 + * 2 3 + * 4 5 6 7 + * 8 9 10 11 12 13 14 15 + * + * 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 + */ + +//$arrTree = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; +//$arrTree = range(1, 127, 1); +//$arrTree = [1, 2, 3, 4, 5, null, 7]; //$arrTree = [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4]; +//$arrTree = range(1, 63, 1); //$a = new BinaryTree($arrTree); -//print_r($a); +////print_r($a->treeHeight($a) . '|'); +//$a->printTree($a); From d203b2a0362e15c30d149d8a1c97da6d81cbda72 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sat, 26 Dec 2020 00:02:15 +0800 Subject: [PATCH 148/192] add debug --- Lib/BinaryTree.php | 1 + 1 file changed, 1 insertion(+) diff --git a/Lib/BinaryTree.php b/Lib/BinaryTree.php index 2522d2e8..fe54e818 100644 --- a/Lib/BinaryTree.php +++ b/Lib/BinaryTree.php @@ -36,6 +36,7 @@ function printTree($root) { //计算树高 $treeHeight = $this->treeHeight($root); + //print_r('树高:' . $treeHeight . PHP_EOL); //层序遍历计算原坐标 $queue = new SplQueue(); From 92cd755e16b2f7496bf3437fab017bb8d5a38374 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sat, 26 Dec 2020 01:14:30 +0800 Subject: [PATCH 149/192] fixed --- Lib/BinaryTree.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Lib/BinaryTree.php b/Lib/BinaryTree.php index fe54e818..defc3ef2 100644 --- a/Lib/BinaryTree.php +++ b/Lib/BinaryTree.php @@ -60,8 +60,9 @@ function printTree($root) //计算新坐标 $dp = []; for ($i = $treeHeight - 1; $i >= 0; $i--) { - for ($j = 0; $j < count($arrTree[$i]); $j++) { + for ($j = 0; $j < 2 ** $i; $j++) { if ($i == count($arrTree) - 1) { + //print_r('i:' . $i . '|j:' . $j . '|v:' . 2 ** $i . PHP_EOL); $dp[$i][$j] = [$i, 2 * $j]; } else { $dp[$i][$j] = [$i, ($dp[$i + 1][2 * $j][1] + $dp[$i + 1][2 * $j + 1][1]) / 2]; From 4467e53da1ba1ebed7687f0146670f02b4b707e3 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sat, 26 Dec 2020 02:54:39 +0800 Subject: [PATCH 150/192] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E5=9F=BA=E4=BA=8E?= =?UTF-8?q?=E6=95=B0=E7=BB=84=E5=88=9B=E5=BB=BA=E7=9A=84=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Lib/BinaryTree.php | 77 ++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 75 insertions(+), 2 deletions(-) diff --git a/Lib/BinaryTree.php b/Lib/BinaryTree.php index defc3ef2..69f9b56d 100644 --- a/Lib/BinaryTree.php +++ b/Lib/BinaryTree.php @@ -9,7 +9,8 @@ class BinaryTree public function __construct($arrTree) { - $root = $this->createTree($arrTree, 0); + //$root = $this->createTree($arrTree, 0); + $root = $this->createTree3($arrTree); $this->val = $root->val; $this->left = $root->left; $this->right = $root->right; @@ -21,6 +22,7 @@ function createTree($arrTree, $i) $root = new TreeNode($arrTree[$i]); $left = 2 * $i + 1; $right = 2 * $i + 2; + //print_r('i:' . $i . '->' . ($arrTree[$i] ?? 'null') . '|L:' . $left . '->' . ($arrTree[$left] ?? 'null') . '|R:' . $right . '->' . ($arrTree[$right] ?? 'null') . PHP_EOL); $rootLeft = $this->createTree($arrTree, $left); if ($rootLeft && !is_null($rootLeft->val)) { $root->left = $rootLeft; @@ -32,6 +34,77 @@ function createTree($arrTree, $i) return $root; } + function createTree2($arrTree) + { + $queue = new SplQueue(); + $root = new TreeNode($arrTree[0]); + $queue->enqueue($root); + $levelNodeNum = 2; //注意不一定是2的幂,是上一行非空节点的数量乘2 + $startIndex = 1; + $restNodeNum = count($arrTree) - 1; + while ($restNodeNum > 0) { + for ($i = $startIndex; $i < $startIndex + $levelNodeNum; $i = $i + 2) { + if ($i == count($arrTree)) { +// echo '1'; +// print_r($root); + return $root; + } + $node = $queue->dequeue(); + if (!is_null($arrTree[$i])) { + $node->left = new TreeNode($arrTree[$i]); + $queue->enqueue($node->left); + } + if ($i + 1 == count($arrTree)) { +// echo '2'; +// print_r($root); + return $root; + } + if (!is_null($arrTree[$i + 1])) { + $node->right = new TreeNode($arrTree[$i + 1]); + $queue->enqueue($node->right); + } + } + $startIndex += $levelNodeNum; + $restNodeNum -= $levelNodeNum; + $levelNodeNum = 2 * $queue->count(); + } +// echo '3'; +// print_r($root); + return $root; + } + + function createTree3($arrTree) + { + $queue = new SplQueue(); + $root = new TreeNode($arrTree[0]); + $queue->enqueue($root); + $levelNodeNum = 2; //注意不一定是2的幂,是上一行非空节点的数量乘2 + $startIndex = 1; + while (!$queue->isEmpty()) { + for ($i = $startIndex; $i < $startIndex + $levelNodeNum; $i = $i + 2) { + if ($i == count($arrTree)) { + print_r($root); + return $root; + } + $node = $queue->dequeue(); + if (!is_null($arrTree[$i])) { + $node->left = new TreeNode($arrTree[$i]); + $queue->enqueue($node->left); + } + if ($i + 1 == count($arrTree)) { + return $root; + } + if (!is_null($arrTree[$i + 1])) { + $node->right = new TreeNode($arrTree[$i + 1]); + $queue->enqueue($node->right); + } + } + $startIndex += $levelNodeNum; + $levelNodeNum = 2 * $queue->count(); + } + return $root; + } + function printTree($root) { //计算树高 @@ -65,7 +138,7 @@ function printTree($root) //print_r('i:' . $i . '|j:' . $j . '|v:' . 2 ** $i . PHP_EOL); $dp[$i][$j] = [$i, 2 * $j]; } else { - $dp[$i][$j] = [$i, ($dp[$i + 1][2 * $j][1] + $dp[$i + 1][2 * $j + 1][1]) / 2]; + $dp[$i][$j] = [$i, ($dp[$i + 1][2 * $j][1] + $dp[$i + 1][2 * $j + 1][1]) / 2]; //仅适用于完全二叉树 } } } From 290f7540c8861c5468c596785786c96ca70cdc72 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sat, 26 Dec 2020 04:23:49 +0800 Subject: [PATCH 151/192] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=B8=A6=E6=A0=91?= =?UTF-8?q?=E6=9E=9D=E6=89=93=E5=8D=B0=E4=BA=8C=E5=8F=89=E6=A0=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Lib/BinaryTree.php | 84 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 83 insertions(+), 1 deletion(-) diff --git a/Lib/BinaryTree.php b/Lib/BinaryTree.php index 69f9b56d..9de33f8c 100644 --- a/Lib/BinaryTree.php +++ b/Lib/BinaryTree.php @@ -83,7 +83,6 @@ function createTree3($arrTree) while (!$queue->isEmpty()) { for ($i = $startIndex; $i < $startIndex + $levelNodeNum; $i = $i + 2) { if ($i == count($arrTree)) { - print_r($root); return $root; } $node = $queue->dequeue(); @@ -105,6 +104,10 @@ function createTree3($arrTree) return $root; } + /** + * 不带树枝打印 非完全二叉树 行不通 + * @param $root + */ function printTree($root) { //计算树高 @@ -172,6 +175,83 @@ function printTree($root) } } + /** + * 带树枝打印 + * https://cloud.tencent.com/developer/ask/60848 + * @param $root + */ + function showTree($root) + { + $treeHeight = $this->treeHeight($root); + $this->printNodeInternal([$root], 1, $treeHeight); + } + + function printNodeInternal($nodes, $level, $maxLevel) + { + if (empty($nodes) || $this->isAllElementNull($nodes)) return; + $floor = $maxLevel - $level; + $endLine = 2 ** max($floor - 1, 0); + $firstSpaces = 2 ** $floor - 1; + $betweenSpaces = 2 ** ($floor + 1) - 1; + $this->printWhiteSpaces($firstSpaces); + $newNodes = []; + foreach ($nodes as $node) { + if ($node) { + echo $node->val; + $newNodes[] = $node->left; + $newNodes[] = $node->right; + } else { + $newNodes[] = null; + $newNodes[] = null; + echo ' '; + } + $this->printWhiteSpaces($betweenSpaces); + } + echo PHP_EOL; + for ($i = 1; $i <= $endLine; $i++) { + for ($j = 0; $j < count($nodes); $j++) { + $this->printWhiteSpaces($firstSpaces - $i); + if (!$nodes[$j]) { + $this->printWhiteSpaces($endLine + $endLine + $i + 1); + continue; + } + + if ($nodes[$j]->left) { + echo '/'; + } else { + $this->printWhiteSpaces(1); + } + + $this->printWhiteSpaces($i + $i - 1); + + if ($nodes[$j]->right) { + echo '\\'; + } else { + $this->printWhiteSpaces(1); + } + $this->printWhiteSpaces($endLine + $endLine - $i); + } + echo PHP_EOL; + } + $this->printNodeInternal($newNodes, $level + 1, $maxLevel); + } + + function printWhiteSpaces($count) + { + for ($i = 0; $i < $count; $i++) { + echo ' '; + } + } + + function isAllElementNull($list) + { + foreach ($list as $obj) { + if ($obj) return false; + } + return true; + } + + function treeHeight($root) { if (!$root) return 0; @@ -214,6 +294,8 @@ function treeHeight($root) //$arrTree = [1, 2, 3, 4, 5, null, 7]; //$arrTree = [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4]; //$arrTree = range(1, 63, 1); +//$arrTree = [1, 2, 3, 4, null, null, 7, 8, 9, null, 15]; //$a = new BinaryTree($arrTree); ////print_r($a->treeHeight($a) . '|'); //$a->printTree($a); +//$a->showTree($a); From 1b7c860805514d40244ac00ce3c2c6a03f0845ef Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sat, 26 Dec 2020 04:38:24 +0800 Subject: [PATCH 152/192] =?UTF-8?q?optimize=20=E5=A2=9E=E5=8A=A0=E5=B8=A6?= =?UTF-8?q?=E9=A2=9C=E8=89=B2=E8=87=AA=E6=8F=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Lib/BinaryTree.php | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Lib/BinaryTree.php b/Lib/BinaryTree.php index 9de33f8c..1064d5b8 100644 --- a/Lib/BinaryTree.php +++ b/Lib/BinaryTree.php @@ -197,7 +197,8 @@ function printNodeInternal($nodes, $level, $maxLevel) $newNodes = []; foreach ($nodes as $node) { if ($node) { - echo $node->val; + $this->displayColorText($node->val); + //echo $node->val; $newNodes[] = $node->left; $newNodes[] = $node->right; } else { @@ -251,6 +252,10 @@ function isAllElementNull($list) return true; } + function displayColorText($txt) + { + echo "\e[34m" . $txt . "\e[0m"; + } function treeHeight($root) { From 4bf9b066544b0906b2d1ffbdf973cf82999dc9ec Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sat, 26 Dec 2020 05:16:39 +0800 Subject: [PATCH 153/192] =?UTF-8?q?=E6=9C=80=E9=95=BF=E5=90=8C=E5=80=BC?= =?UTF-8?q?=E8=B7=AF=E5=BE=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week6/687.longest-univalue-path.php | 132 ++++++++++++++++++++++++++++ 1 file changed, 132 insertions(+) create mode 100644 Week6/687.longest-univalue-path.php diff --git a/Week6/687.longest-univalue-path.php b/Week6/687.longest-univalue-path.php new file mode 100644 index 00000000..65ee8f7b --- /dev/null +++ b/Week6/687.longest-univalue-path.php @@ -0,0 +1,132 @@ +val = $val; + * $this->left = $left; + * $this->right = $right; + * } + * } + */ +class Solution +{ + + /** + * @param TreeNode $root + * @return Integer + */ + function longestUnivaluePath($root) + { + $ans = 0; + $this->dfs2($root, $ans); + return $ans; + } + + /** + * @param $root + * @param $ans + * @return int|mixed + */ + function dfs3($root, &$ans) + { + if (!$root) return 0; + $maxLength = 0; //以root为起点的最长同值路径 + $left = $this->dfs3($root->left, $ans); // 以root.left为起点的最长同值路径 + $right = $this->dfs3($root->right, $ans); // 以root.right为起点的最长同值路径 + + if ($root->left && $root->left->val == $root->val) { + $maxLength = max($maxLength, $left + 1); + } + + if ($root->right && $root->right->val == $root->val) { + $maxLength = max($maxLength, $right + 1); + } + + //不需要更新maxLength 但要更新ans + if ($root->left && $root->left->val == $root->val && $root->right && $root->right->val == $root->val) { + $ans = max($ans, $left + $right + 2); + } + + $ans = max($ans, $maxLength); + return $maxLength; + } + + /** + * @param $root + * @param $ans + * @return int|mixed + */ + function dfs2($root, &$ans) + { + if (!$root) return 0; + $left = $this->dfs2($root->left, $ans); + $right = $this->dfs2($root->right, $ans); + + $maxLeft = $root->left && $root->left->val == $root->val ? $left + 1 : 0; + $maxRight = $root->right && $root->right->val == $root->val ? $right + 1 : 0; + $ans = max($ans, $maxLeft + $maxRight); + return max($maxLeft, $maxRight); + } + + /** + * + * @param $root + * @param $ans + * @return int|mixed + */ + function dfs($root, &$ans) + { + if (!$root) return 0; + $left = $this->dfs($root->left, $ans); // 以root.left为起点的最长同值路径 + $right = $this->dfs($root->right, $ans); // 以root.right为起点的最长同值路径 + + $curLeft = $curRight = 0; + if ($root->left && $root->left->val == $root->val) { + $curLeft += $left + 1; + } + if ($root->right && $root->right->val == $root->val) { + $curRight += $right + 1; + } + print_r('l:' . $left . '|r:' . $right . '|cl:' . $curLeft . '|cr:' . $curRight . PHP_EOL); + $ans = max($ans, $curLeft + $curRight); + return max($curLeft, $curRight); + } +} + +/** + *输入: + * 5 + * / \ + * 4 5 + * / \ \ + * 1 1 5 + * 输出: 2 + * + * 输入: + * 1 + * / \ + * 4 5 + * / \ \ + * 4 4 5 + * + * 输出: 2 + */ + +$tree = [5, 4, 5, 1, 1, null, 5]; //2 +$tree = [1, 4, 5, 4, 4, null, 5]; //2 +$tree = [5, 4, 5, 4, 4, 5, 3, 4, 4, null, null, null, 4, null, null, 4]; +$tree = [1, 2, 3, 4, 5, 6, 7, 8, 9, null, null, null, 13, null, null, 16, null, null, 18, null, 20, 21, null, null, 24, 25]; +$tree = [1, 2, 3, 4, null, null, 7, 8, 9, null, 15]; +$tree = [5, 4, 5, 4, 4, 5, 3, 4, 4, null, null, null, 4, null, null, 4, null, null, 4, null, 4, 4, null, null, 4, 4]; //6 +$tree = [5, 4, 5, 4, 4, 5, 3, 4, 4, null, null, null, 4, null, null, 4, null, null, 4, null, 4, 4, null, null, 4, 4]; //6 +$root = new BinaryTree($tree); +$ret = (new Solution())->longestUnivaluePath($root); +//print_r($root->showTree($root)); +print_r($ret); + From 0ac9e4499a220a05abbaa9eebcc392a15e53fe52 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sat, 26 Dec 2020 18:29:18 +0800 Subject: [PATCH 154/192] optimize --- Lib/BinaryTree.php | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/Lib/BinaryTree.php b/Lib/BinaryTree.php index 1064d5b8..14c2d0bb 100644 --- a/Lib/BinaryTree.php +++ b/Lib/BinaryTree.php @@ -6,6 +6,7 @@ class BinaryTree public $val = null; public $left = null; public $right = null; + public $maxWidth = 1; public function __construct($arrTree) { @@ -204,7 +205,7 @@ function printNodeInternal($nodes, $level, $maxLevel) } else { $newNodes[] = null; $newNodes[] = null; - echo ' '; + $this->echoWidthTxt(' '); } $this->printWhiteSpaces($betweenSpaces); } @@ -218,7 +219,7 @@ function printNodeInternal($nodes, $level, $maxLevel) } if ($nodes[$j]->left) { - echo '/'; + $this->echoWidthTxt('/'); } else { $this->printWhiteSpaces(1); } @@ -226,7 +227,7 @@ function printNodeInternal($nodes, $level, $maxLevel) $this->printWhiteSpaces($i + $i - 1); if ($nodes[$j]->right) { - echo '\\'; + $this->echoWidthTxt('\\'); } else { $this->printWhiteSpaces(1); } @@ -240,7 +241,7 @@ function printNodeInternal($nodes, $level, $maxLevel) function printWhiteSpaces($count) { for ($i = 0; $i < $count; $i++) { - echo ' '; + $this->echoWidthTxt(' '); } } @@ -252,14 +253,27 @@ function isAllElementNull($list) return true; } + function echoWidthTxt($txt, $width = 1, $echo = 1) + { + $width = $this->maxWidth; + $txt = sprintf("%' " . $width . "s", $txt); + if ($echo) { + echo $txt; + } else { + return $txt; + } + } + function displayColorText($txt) { + $txt = $this->echoWidthTxt($txt, $this->maxWidth, 0); echo "\e[34m" . $txt . "\e[0m"; } function treeHeight($root) { if (!$root) return 0; + $this->maxWidth = max($this->maxWidth, strlen($root->val)); return max($this->treeHeight($root->left), $this->treeHeight($root->right)) + 1; } From 674472260844ae1b3a05e1fe5e6a1ed1c5ee4824 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 30 Dec 2020 00:03:42 +0800 Subject: [PATCH 155/192] =?UTF-8?q?=E7=9F=A9=E5=BD=A2=E5=8C=BA=E5=9F=9F?= =?UTF-8?q?=E4=B8=8D=E8=B6=85=E8=BF=87K=E7=9A=84=E6=9C=80=E5=A4=A7?= =?UTF-8?q?=E6=95=B0=E5=80=BC=E5=92=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ....max-sum-of-rectangle-no-larger-than-k.php | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 Week7/363.max-sum-of-rectangle-no-larger-than-k.php diff --git a/Week7/363.max-sum-of-rectangle-no-larger-than-k.php b/Week7/363.max-sum-of-rectangle-no-larger-than-k.php new file mode 100644 index 00000000..0e753e04 --- /dev/null +++ b/Week7/363.max-sum-of-rectangle-no-larger-than-k.php @@ -0,0 +1,74 @@ +dpMax($rowSum, $k)); + if ($ans == $k) return $k; // 尽量提前 + } + } + return $ans; + } + + /** + * 求不大于k的最大子区间和 二分查找 + * preSum[i,j] = preSum[0,j] - preSum[0,i] <= k + * preSum[0,j] - k <= preSum[0,i] + * 首先想起来前缀和求法sum[j]-sum[i],可以理解成 大面积-小面积 + * 结合起题目来就是 大-小<=k 而稍微变化一下就是 小>=大-k + * 我们主要找的就是符合的小面积,而且要想最逼近k,在大面积一定情况下,小面积越小越好 + * @param $arr + * @param $k + */ + function dpMax($arr, $k) + { + $preSum = 0; + $rollMax = PHP_INT_MIN; + for ($i = 0; $i < count($arr); $i++) { + $preSum = max($preSum + $arr[$i], $arr[$i]); + $rollMax = max($rollMax, $preSum); + } + if ($rollMax <= $k) return $rollMax; + $ans = PHP_INT_MIN; + for ($i = 0; $i < count($arr); $i++) { + $preSum = 0; + for ($j = $i; $j < count($arr); $j++) { + $preSum += $arr[$j]; + if ($preSum > $ans && $preSum <= $k) $ans = $preSum; //更新答案 + if($ans == $k) return $k; //尽量提前 + } + } + return $ans; + } +} + +/** + * 输入: matrix = [[1,0,1],[0,-2,3]], k = 2 + * 输出: 2 + * 解释:矩形区域[[0, 1], [-2, 3]]的数值和是 2,且 2 是不超过 k 的最大数字(k = 2)。 + * matrix = [[2,2,-1]], k = 0 // -1 + */ + +$matrix = [[1, 0, 1], [0, -2, 3]]; +$k = 2; +$matrix = [[2, 2, -1]]; +$k = 0; +$ret = (new Solution())->maxSumSubmatrix($matrix, $k); +print_r($ret); \ No newline at end of file From 08a13a8a85f1b7c5dcf3a044719a91bc5c6f3ebc Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 30 Dec 2020 18:50:06 +0800 Subject: [PATCH 156/192] =?UTF-8?q?=E6=9C=80=E5=90=8E=E4=B8=80=E5=9D=97?= =?UTF-8?q?=E7=9F=B3=E5=A4=B4=E9=87=8D=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week7/1046.last-stone-weight.php | 39 ++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Week7/1046.last-stone-weight.php diff --git a/Week7/1046.last-stone-weight.php b/Week7/1046.last-stone-weight.php new file mode 100644 index 00000000..6087329d --- /dev/null +++ b/Week7/1046.last-stone-weight.php @@ -0,0 +1,39 @@ +insert($stone); + } + while ($heap->count() > 1) { + $s1 = $heap->extract(); + $s2 = $heap->extract(); + if ($s1 > $s2) { + $heap->insert($s1 - $s2); + } + } + return $heap->isEmpty() ? 0 : $heap->top(); + } +} + +/** + * 输入:[2,7,4,1,8,1] + * 输出:1 + * 解释: + * 先选出 7 和 8,得到 1,所以数组转换为 [2,4,1,1,1], + * 再选出 2 和 4,得到 2,所以数组转换为 [2,1,1,1], + * 接着是 2 和 1,得到 1,所以数组转换为 [1,1,1], + * 最后选出 1 和 1,得到 0,最终数组转换为 [1],这就是最后剩下那块石头的重量。 + */ +$stones = [2, 7, 4, 1, 8, 1]; //1 +$ret = (new Solution())->lastStoneWeight($stones); +print_r($ret); From 9cf7440b3b114229fa3d554824d1017c68b47dac Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 31 Dec 2020 07:14:49 +0800 Subject: [PATCH 157/192] =?UTF-8?q?=E5=AE=9E=E7=8E=B0Trie=E6=A0=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week7/208.implement-trie-prefix-tree.php | 167 +++++++++++++++++++++++ 1 file changed, 167 insertions(+) create mode 100644 Week7/208.implement-trie-prefix-tree.php diff --git a/Week7/208.implement-trie-prefix-tree.php b/Week7/208.implement-trie-prefix-tree.php new file mode 100644 index 00000000..30afbe1e --- /dev/null +++ b/Week7/208.implement-trie-prefix-tree.php @@ -0,0 +1,167 @@ +isEnd = false; + //$this->children = array_fill(0, 26, null); //这种也可以 感觉有点浪费 + $this->children = []; + } + + /** + * Inserts a word into the trie. + * @param String $word + * @return NULL + */ + function insert($word) + { + $node = $this; + for ($i = 0; $i < strlen($word); $i++) { + $index = ord($word[$i]) - ord('a'); + if (!isset($node->children[$index])) { + $node->children[$index] = new Trie(); + } + //每个节点都是必须要有的 + $node = $node->children[$index]; + } + $node->isEnd = true; + } + + /** + * Returns if the word is in the trie. + * @param String $word + * @return Boolean + */ + function search($word) + { + $node = $this; + for ($i = 0; $i < strlen($word); $i++) { + $index = ord($word[$i]) - ord('a'); + if (isset($node->children[$index])) { + $node = $node->children[$index]; + } else { + return false; + } + } + return $node->isEnd; + } + + /** + * Returns if there is any word in the trie that starts with the given prefix. + * @param String $prefix + * @return Boolean + */ + function startsWith($prefix) + { + $node = $this; + for ($i = 0; $i < strlen($prefix); $i++) { + $index = ord($prefix[$i]) - ord('a'); + if (isset($node->children[$index])) { + $node = $node->children[$index]; + } else { + return false; + } + } + return true; + } +} + +class Trie +{ + /** + * Initialize your data structure here. + */ + function __construct() + { + $this->root = new TrieNode(); + } + + /** + * Inserts a word into the trie. + * @param String $word + * @return NULL + */ + function insert($word) + { + $node = $this->root; + for ($i = 0; $i < strlen($word); $i++) { + $index = ord($word[$i]) - ord('a'); + if (!isset($node->children[$index])) { + $node->children[$index] = new TrieNode(); + } + //每个节点都是必须要有的 + $node = $node->children[$index]; + } + $node->isEnd = true; + } + + /** + * Returns if the word is in the trie. + * @param String $word + * @return Boolean + */ + function search($word) + { + $node = $this->root; + for ($i = 0; $i < strlen($word); $i++) { + $index = ord($word[$i]) - ord('a'); + if (isset($node->children[$index])) { + $node = $node->children[$index]; + } else { + return false; + } + } + return $node->isEnd; + } + + /** + * Returns if there is any word in the trie that starts with the given prefix. + * @param String $prefix + * @return Boolean + */ + function startsWith($prefix) + { + $node = $this->root; + for ($i = 0; $i < strlen($prefix); $i++) { + $index = ord($prefix[$i]) - ord('a'); + if (isset($node->children[$index])) { + $node = $node->children[$index]; + } else { + return false; + } + } + return true; + } +} + +/** + * 将节点分出来 执行更快 占用空间更少 + * Class TrieNode + */ +class TrieNode +{ + public $isEnd = false; + public $children = []; +} + +/** + * Your Trie object will be instantiated and called as such: + * $obj = Trie(); + * $obj->insert($word); + * $ret_2 = $obj->search($word); + * $ret_3 = $obj->startsWith($prefix); + */ + +$obj = new Trie(); +$obj->insert('apple'); +//$obj->insert('apc'); +//print_r($obj); +var_dump($obj->search('apple')); //true +var_dump($obj->search('app')); //false +var_dump($obj->startsWith('app')); //true +$obj->insert('app'); +var_dump($obj->search('app')); //true From f130f5030e619259067aa6145179a6082e413dd8 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 31 Dec 2020 08:40:07 +0800 Subject: [PATCH 158/192] =?UTF-8?q?=E5=8D=95=E8=AF=8D=E6=90=9C=E7=B4=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week7/79.word-search.php | 144 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 144 insertions(+) create mode 100644 Week7/79.word-search.php diff --git a/Week7/79.word-search.php b/Week7/79.word-search.php new file mode 100644 index 00000000..45930a18 --- /dev/null +++ b/Week7/79.word-search.php @@ -0,0 +1,144 @@ +backTrace($board, $visited, $i, $j, $word, 0); + if ($flag) return true; + } + } + return false; + } + + /** + * 从board[i][j] 开始深度优先搜索 word[k] + * @param $board + * @param $visited + * @param $i + * @param $j + * @param $word + * @param $k + */ + function backTrace($board, &$visited, $i, $j, $word, $k) + { + if ($board[$i][$j] != $word[$k]) { + return false; + } elseif ($k == strlen($word) - 1) { + return true; + } + $visited[$i][$j] = 1; //相当于 将原坐标值 $tmp 修改 $board[$i][$j] = '.'; + $h = count($board); + $w = count($board[0]); + $dx = [-1, 0, 1, 0]; + $dy = [0, -1, 0, 1]; + $result = false; + for ($di = 0; $di < 4; $di++) { + $nx = $i + $dx[$di]; + $ny = $j + $dy[$di]; + if ($nx >= 0 && $ny >= 0 && $nx < $h && $ny < $w && !$visited[$nx][$ny]) { + $flag = $this->backTrace($board, $visited, $nx, $ny, $word, $k + 1); + if ($flag) { //4个方向某一个方向能找到就返回true; + $result = true; + break; + } + } + } + $visited[$i][$j] = 0; //相当于将原坐标值 $tmp 复原 $board[$i][$j] = $tmp; + return $result; + } + + /** + * @param String[][] $board + * @param String $word + * @return Boolean + */ + function exist2($board, $word) + { + //字母板长宽 + $this->rows = count($board); + $this->cols = count($board[0]); + + for ($i = 0; $i < $this->rows; $i++) { + for ($j = 0; $j < $this->cols; $j++) { + if ($this->find($board, $word, $i, $j, 0)) { + return true; + } + } + } + + return false; + } + + function find(&$board, $word, $i, $j, $index) + { + //当前位置字母不是目标字母,返回继续遍历 + if ($board[$i][$j] != $word[$index]) { + return false; + } + + //成功找到最后一个字母,返回 + if ($index == strlen($word) - 1) { + return true; + } + + //标记当前的字母 + $ori = $word[$index]; + $board[$i][$j] = "."; + + //从四个方向依次遍历 + //检查是否出界和是否搜寻过 + if ($i - 1 >= 0 && $board[$i - 1][$j] != ".") { + if ($this->find($board, $word, $i - 1, $j, $index + 1)) return true; + } + if ($j - 1 >= 0 && $board[$i][$j - 1] != ".") { + if ($this->find($board, $word, $i, $j - 1, $index + 1)) return true; + } + if ($i + 1 < $this->rows && $board[$i + 1][$j] != ".") { + if ($this->find($board, $word, $i + 1, $j, $index + 1)) return true; + } + if ($j + 1 < $this->cols && $board[$i][$j + 1] != ".") { + if ($this->find($board, $word, $i, $j + 1, $index + 1)) return true; + } + + //没找到目标字母,还原当前字母 + $board[$i][$j] = $ori; + return false; + } +} + +/** + * board = + * [ + * ['A','B','C','E'], + * ['S','F','C','S'], + * ['A','D','E','E'] + * ] + * 给定 word = "ABCCED", 返回 true + * 给定 word = "SEE", 返回 true + * 给定 word = "ABCB", 返回 false + */ + +$board = + [ + ['A', 'B', 'C', 'E'], + ['S', 'F', 'C', 'S'], + ['A', 'D', 'E', 'E'] + ]; + +$word = 'ABCCED'; +$word = 'SEE'; +$ret = (new Solution())->exist($board, $word); +var_dump($ret); From a70193a4ca7a52317e371b9828298c1651acfc63 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 31 Dec 2020 08:42:58 +0800 Subject: [PATCH 159/192] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=AD=97=E7=AC=A6?= =?UTF-8?q?=E4=B8=B2=E9=95=BF=E5=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week7/79.word-search.php | 1 + 1 file changed, 1 insertion(+) diff --git a/Week7/79.word-search.php b/Week7/79.word-search.php index 45930a18..79c2f6c9 100644 --- a/Week7/79.word-search.php +++ b/Week7/79.word-search.php @@ -4,6 +4,7 @@ class Solution { /** + * O(MN3^L) O(MN) M,N为网格长宽 L为字符串长度 * @param String[][] $board * @param String $word * @return Boolean From 893c6e8c4ac9cd9d4a9527ac5769f4223b12d77a Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 31 Dec 2020 10:00:07 +0800 Subject: [PATCH 160/192] =?UTF-8?q?=E5=8D=95=E8=AF=8D=E6=90=9C=E7=B4=A2II?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week7/212.word-search-ii.php | 80 ++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 Week7/212.word-search-ii.php diff --git a/Week7/212.word-search-ii.php b/Week7/212.word-search-ii.php new file mode 100644 index 00000000..81656e7f --- /dev/null +++ b/Week7/212.word-search-ii.php @@ -0,0 +1,80 @@ +insert($word); + } + + $row = count($board); + $col = count($board[0]); + + $res = []; + for ($i = 0; $i < $row; $i++) { + for ($j = 0; $j < $col; $j++) { + $index = ord($board[$i][$j]) - ord('a'); + if (isset($trie->root->children[$index])) { + $this->dfs($board, $i, $j, $trie->root, $res); + } + } + } + return $res; + } + + function dfs(&$board, $i, $j, $root, &$res) + { + if ($i < 0 || $j < 0 || $i >= count($board) || $j >= count($board[0])) return; + $char = $board[$i][$j]; + if ($char == '.') return; + + $index = ord($char) - ord('a'); + if (isset($root->children[$index])) { + $node = $root->children[$index]; + if ($node->isEnd) { + $res[] = $node->word; + unset($root->children[$index]);//防止重复加入 这个快 + //$node->isEnd = false; //防止重复加入 这个特别慢 + } + } else { + return; + } + + $board[$i][$j] = '.'; + $this->dfs($board, $i - 1, $j, $node, $res); + $this->dfs($board, $i + 1, $j, $node, $res); + $this->dfs($board, $i, $j - 1, $node, $res); + $this->dfs($board, $i, $j + 1, $node, $res); + $board[$i][$j] = $char; + } +} + +/** + * 输入:board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"] + * 输出:["eat","oath"] + * + * 输入:[["a","a"]] , ["a"] + * 输出: ["a"] + * + */ + +$board = [ + ["o", "a", "a", "n"], + ["e", "t", "a", "e"], + ["i", "h", "k", "r"], + ["i", "f", "l", "v"] +]; +$words = ["oath", "pea", "eat", "rain"]; +$board = [["a", "a"]]; +$words = ["a"]; +$ret = (new Solution())->findWords($board, $words); +print_r($ret); From 0457cc5d3b4af11e19262325003fa9793849447b Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 31 Dec 2020 10:01:22 +0800 Subject: [PATCH 161/192] add Trie --- Lib/Trie.php | 72 ++++++++++++++++++++++++++++++++++++++++++++++++ Lib/TrieNode.php | 9 ++++++ 2 files changed, 81 insertions(+) create mode 100644 Lib/Trie.php create mode 100644 Lib/TrieNode.php diff --git a/Lib/Trie.php b/Lib/Trie.php new file mode 100644 index 00000000..bba3e62c --- /dev/null +++ b/Lib/Trie.php @@ -0,0 +1,72 @@ +root = new TrieNode(); + } + + /** + * Inserts a word into the trie. + * @param String $word + * @return NULL + */ + function insert($word) + { + $node = $this->root; + for ($i = 0; $i < strlen($word); $i++) { + $index = ord($word[$i]) - ord('a'); + if (!isset($node->children[$index])) { + $node->children[$index] = new TrieNode(); + } + //每个节点都是必须要有的 + $node = $node->children[$index]; + } + $node->isEnd = true; + $node->word = $word; + } + + /** + * Returns if the word is in the trie. + * @param String $word + * @return Boolean + */ + function search($word) + { + $node = $this->root; + for ($i = 0; $i < strlen($word); $i++) { + $index = ord($word[$i]) - ord('a'); + if (isset($node->children[$index])) { + $node = $node->children[$index]; + } else { + return false; + } + } + return $node->isEnd; + } + + /** + * Returns if there is any word in the trie that starts with the given prefix. + * @param String $prefix + * @return Boolean + */ + function startsWith($prefix) + { + $node = $this->root; + for ($i = 0; $i < strlen($prefix); $i++) { + $index = ord($prefix[$i]) - ord('a'); + if (isset($node->children[$index])) { + $node = $node->children[$index]; + } else { + return false; + } + } + return true; + } +} + diff --git a/Lib/TrieNode.php b/Lib/TrieNode.php new file mode 100644 index 00000000..1a8f3be4 --- /dev/null +++ b/Lib/TrieNode.php @@ -0,0 +1,9 @@ + Date: Thu, 31 Dec 2020 10:09:52 +0800 Subject: [PATCH 162/192] =?UTF-8?q?=E5=8D=95=E8=AF=8D=E6=90=9C=E7=B4=A2II?= =?UTF-8?q?=20=E6=97=B6=E9=97=B4=E5=A4=8D=E6=9D=82=E5=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week7/212.word-search-ii.php | 1 + 1 file changed, 1 insertion(+) diff --git a/Week7/212.word-search-ii.php b/Week7/212.word-search-ii.php index 81656e7f..a4200314 100644 --- a/Week7/212.word-search-ii.php +++ b/Week7/212.word-search-ii.php @@ -5,6 +5,7 @@ class Solution { /** + * O(MN * 4 * 3^(L-1)) O(N) * @param String[][] $board * @param String[] $words * @return String[] From e790034afddb50fa8a017a8e94360947a62e6ff8 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 31 Dec 2020 10:54:20 +0800 Subject: [PATCH 163/192] =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E4=B8=AD?= =?UTF-8?q?=E7=9A=84=E6=9C=80=E5=A4=A7=E8=B7=AF=E5=BE=84=E5=92=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week7/124.binary-tree-maximum-path-sum.php | 97 ++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 Week7/124.binary-tree-maximum-path-sum.php diff --git a/Week7/124.binary-tree-maximum-path-sum.php b/Week7/124.binary-tree-maximum-path-sum.php new file mode 100644 index 00000000..8e0d8518 --- /dev/null +++ b/Week7/124.binary-tree-maximum-path-sum.php @@ -0,0 +1,97 @@ +val = $val; + * $this->left = $left; + * $this->right = $right; + * } + * } + */ +class Solution +{ + + /** + * @param TreeNode $root + * @return Integer + */ + function maxPathSum($root) + { + $res = PHP_INT_MIN; + $this->maxGain($root, $res); + return $res; + } + + function maxGain($root, &$res) + { + if (!$root) return 0; + $left = max($this->maxGain($root->left, $res), 0); //为什么要和0比较 因为左节点值为负数可以不选 + $right = max($this->maxGain($root->right, $res), 0); + //print_r('root->val:' . $root->val . '|L:' . $left . '|R:' . $right . PHP_EOL); + $res = max($res, $root->val + $left + $right); + return $root->val + max($left, $right); + } + + public $max = PHP_INT_MIN; + + /** + * @param TreeNode $root + * @return Integer + */ + function maxPathSum2($root) + { + $this->maxPathSumHelper($root); + return $this->max; + + } + + function maxPathSumHelper($root) + { + if (null == $root) { + return 0; + } + + $rightMax = 0; + if ($root->right) { + $rightMax = max($this->maxPathSumHelper($root->right), 0); + } + + $leftMax = 0; + if ($root->left) { + $leftMax = max($this->maxPathSumHelper($root->left), 0); + } + + $allV = $rightMax + $leftMax + $root->val; + echo sprintf("allV=%d max=%d root=%d, leftMax=%d, rightMax=%d\n", $allV, $this->max, $root->val, $leftMax, $rightMax); + + if ($this->max < $allV) { + $this->max = $allV; + } + return max($rightMax, $leftMax) + $root->val; + } +} + + +/** + * 输入:[-10,9,20,null,null,15,7] + * + * -10 + * / \ + * 9 20 + * / \ + * 15 7 + * + * 输出:42 + */ +$tree = [-10, 9, 20, null, null, 15, 7]; //42 +$tree = [2, -1]; //2 +$root = new BinaryTree($tree); +$root->showTree($root); +$ret = (new Solution())->maxPathSum2($root); +print_r($ret); \ No newline at end of file From 8d046fa2f4a9e27e9c4e9a231f70bdc4219326b1 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sun, 3 Jan 2021 22:23:03 +0800 Subject: [PATCH 164/192] =?UTF-8?q?=E6=90=9C=E7=B4=A2=E4=BA=8C=E7=BB=B4?= =?UTF-8?q?=E7=9F=A9=E9=98=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week7/240.search-a-2d-matrix-ii.php | 42 +++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Week7/240.search-a-2d-matrix-ii.php diff --git a/Week7/240.search-a-2d-matrix-ii.php b/Week7/240.search-a-2d-matrix-ii.php new file mode 100644 index 00000000..69bbe52a --- /dev/null +++ b/Week7/240.search-a-2d-matrix-ii.php @@ -0,0 +1,42 @@ += 0 && $col < $nc) { + if ($matrix[$row][$col] == $target) { + return true; + } elseif ($matrix[$row][$col] > $target) { + $row--; + } else { + $col++; + } + } + return false; + } +} + +/** + * 输入:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5 + * 输出:true + * + * 输入:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20 + * 输出:false + */ + +$matrix = [[1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30]]; +$target = 20; +$ret = (new Solution())->searchMatrix($matrix, $target); +var_dump($ret); From d1cf3b009cc6ff112d901ac99a6569b511ebc6c6 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Tue, 5 Jan 2021 17:39:24 +0800 Subject: [PATCH 165/192] =?UTF-8?q?=E7=9C=81=E4=BB=BD=E6=95=B0=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week7/547.number-of-provinces.php | 98 +++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 Week7/547.number-of-provinces.php diff --git a/Week7/547.number-of-provinces.php b/Week7/547.number-of-provinces.php new file mode 100644 index 00000000..5109c285 --- /dev/null +++ b/Week7/547.number-of-provinces.php @@ -0,0 +1,98 @@ +union($i, $j); + } + } + } + return $uf->count(); + } + + /** + * DFS + * @param Integer[][] $isConnected + * @return Integer + */ + function findCircleNum2($isConnected) + { + $n = count($isConnected); + $visited = array_fill(0, $n, 0); + $nums = 0; + for ($i = 0; $i < $n; $i++) { + if ($visited[$i] == 0) { + $this->dfs($isConnected, $visited, $i); + $nums++; + } + } + return $nums; + } + + /** + * BFS + * @param Integer[][] $isConnected + * @return Integer + */ + function findCircleNum3($isConnected) + { + $n = count($isConnected); + $visited = array_fill(0, $n, 0); + $nums = 0; + $queue = new SplQueue(); + for ($i = 0; $i < $n; $i++) { + if ($visited[$i] == 0) { + $queue->enqueue($i); + while(!$queue->isEmpty()) { + $k = $queue->dequeue(); + $visited[$k] = 1; + for($j = 0 ; $j < $n;$j++) { + if($isConnected[$k][$j] == 1 && $visited[$j] == 0) { + $queue->enqueue($j); + } + } + } + $nums++; + } + } + return $nums; + } + + function dfs($isConnected, &$visited, $i) + { + $n = count($isConnected); + for ($j = 0; $j < $n; $j++) { + if ($isConnected[$i][$j] == 1 && $visited[$j] == 0) { + $visited[$j] = 1; + $this->dfs($isConnected, $visited, $j); + } + } + } +} + +/** + * 输入:isConnected = [[1,1,0],[1,1,0],[0,0,1]] + * 输出:2 + * + * 输入:isConnected = [[1,0,0],[0,1,0],[0,0,1]] + * 输出:3 + * + * [[1,0,0,1],[0,1,1,0],[0,1,1,1],[1,0,1,1]] + */ + +$isConnected = [[1, 1, 0], [1, 1, 0], [0, 0, 1]]; +$isConnected = [[1, 0, 0, 1], [0, 1, 1, 0], [0, 1, 1, 1], [1, 0, 1, 1]]; //1 +$ret = (new Solution())->findCircleNum3($isConnected); +print_r($ret); \ No newline at end of file From dd20077bb59ac097ff5a13f5671b309c1d9dc5d6 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Tue, 5 Jan 2021 17:40:05 +0800 Subject: [PATCH 166/192] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=B9=B6=E6=9F=A5?= =?UTF-8?q?=E9=9B=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Lib/UF.php | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Lib/UF.php diff --git a/Lib/UF.php b/Lib/UF.php new file mode 100644 index 00000000..aaac4b57 --- /dev/null +++ b/Lib/UF.php @@ -0,0 +1,46 @@ +count = 0; //连通分量 + $this->parent = []; // 森林 + $this->size = []; // 树大小 + for ($i = 0; $i < $n; $i++) { + $this->parent[$i] = $i; + $this->size[$i] = 1; + $this->count++; + } + } + + function find($x) + { + while ($this->parent[$x] != $x) { + $this->parent[$x] = $this->parent[$this->parent[$x]]; + $x = $this->parent[$x]; + } + return $x; + } + + function union($p, $q) + { + $rootP = $this->find($p); + $rootQ = $this->find($q); + if ($rootP == $rootQ) return; + + if ($this->size[$rootP] > $this->size[$rootQ]) { + $this->parent[$rootQ] = $rootP; + $this->size[$rootP] += $this->size[$rootQ]; + } else { + $this->parent[$rootP] = $rootQ; + $this->size[$rootQ] += $this->size[$rootP]; + } + $this->count--; + } + + function count() + { + return $this->count; + } +} \ No newline at end of file From c5b33bd1133d902c090b59ca7d0f5b6eb213f5b8 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Fri, 8 Jan 2021 15:58:49 +0800 Subject: [PATCH 167/192] =?UTF-8?q?=E8=A2=AB=E5=9B=B4=E7=BB=95=E7=9A=84?= =?UTF-8?q?=E5=8C=BA=E5=9F=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Lib/UF.php | 5 ++ Week7/130.surrounded-regions.php | 121 +++++++++++++++++++++++++++++++ 2 files changed, 126 insertions(+) create mode 100644 Week7/130.surrounded-regions.php diff --git a/Lib/UF.php b/Lib/UF.php index aaac4b57..8101a0b4 100644 --- a/Lib/UF.php +++ b/Lib/UF.php @@ -39,6 +39,11 @@ function union($p, $q) $this->count--; } + function isConnected($p, $q) + { + return $this->find($p) == $this->find($q); + } + function count() { return $this->count; diff --git a/Week7/130.surrounded-regions.php b/Week7/130.surrounded-regions.php new file mode 100644 index 00000000..8bd64193 --- /dev/null +++ b/Week7/130.surrounded-regions.php @@ -0,0 +1,121 @@ +union($this->node($col, $i, $j), $dummyNode); + } else { + //非边界上的O 与其上下左右的O 联通 + if ($i > 0 && $board[$i - 1][$j] == 'O') { + $uf->union($this->node($col, $i - 1, $j), $this->node($col, $i, $j)); + } + if ($i + 1 < $row && $board[$i + 1][$j] == 'O') { + $uf->union($this->node($col, $i + 1, $j), $this->node($col, $i, $j)); + } + if ($j > 0 && $board[$i][$j - 1] == 'O') { + $uf->union($this->node($col, $i, $j - 1), $this->node($col, $i, $j)); + } + if ($j + 1 < $col && $board[$i][$j + 1] == 'O') { + $uf->union($this->node($col, $i, $j + 1), $this->node($col, $i, $j)); + } + } + } + } + } + + for ($i = 0; $i < $row; $i++) { + for ($j = 0; $j < $col; $j++) { + if ($board[$i][$j] == 'O') { + if (!$uf->isConnected($this->node($col, $i, $j), $dummyNode)) { + $board[$i][$j] = 'X'; + } + } + } + } + } + + function node($col, $i, $j) + { + return $i * $col + $j; + } +} + + +/** + * DFS O(MN) O(MN) + * @param String[][] $board + * @return NULL + */ +function solve(&$board) +{ + $row = count($board); + $col = count($board[0]); + for ($i = 0; $i < $row; $i++) { + $this->dfs($board, $i, 0); + $this->dfs($board, $i, $col - 1); + } + for ($j = 1; $j < $col - 1; $j++) { + $this->dfs($board, 0, $j); + $this->dfs($board, $row - 1, $j); + } + for ($i = 0; $i < $row; $i++) { + for ($j = 0; $j < $col; $j++) { + if ($board[$i][$j] == 'O') { + $board[$i][$j] = 'X'; + } + if ($board[$i][$j] == '#') { + $board[$i][$j] = 'O'; + } + } + } +} + +function dfs(&$board, $i, $j) +{ + $row = count($board); + $col = count($board[0]); + if ($i < 0 || $j < 0 || $i >= $row || $j >= $col || $board[$i][$j] != 'O') return; + $board[$i][$j] = '#'; + $this->dfs($board, $i + 1, $j); + $this->dfs($board, $i - 1, $j); + $this->dfs($board, $i, $j + 1); + $this->dfs($board, $i, $j - 1); +} + +/** + * + */ +$board = [ + ['O'], +]; +$board = [ + ['X', 'X', 'X', 'X'], + ['X', 'O', 'O', 'X'], + ['X', 'X', 'O', 'X'], + ['X', 'O', 'X', 'X'], +]; +$board = [ + ["O", "X", "X", "O", "X"], + ["X", "O", "O", "X", "O"], + ["X", "O", "X", "O", "X"], + ["O", "X", "O", "O", "O"], + ["X", "X", "O", "X", "O"] +]; +(new Solution())->solve2($board); +print_r($board); \ No newline at end of file From f0188874cc5b4492e508d390512ce0a2c3ccf04a Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 13 Jan 2021 14:24:26 +0800 Subject: [PATCH 168/192] =?UTF-8?q?=E7=AC=ACK=E5=A4=A7=E5=85=83=E7=B4=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week2/215.kth-largest-element-in-an-array.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Week2/215.kth-largest-element-in-an-array.php b/Week2/215.kth-largest-element-in-an-array.php index e504b09d..1426c1bc 100644 --- a/Week2/215.kth-largest-element-in-an-array.php +++ b/Week2/215.kth-largest-element-in-an-array.php @@ -14,7 +14,7 @@ function findKthLargest1($nums, $k) { $heapSize = $count = count($nums); $this->buildHeap($nums, $heapSize); - for ($i = $count - 1; $i > $count - $k; $i--) { + for ($i = $count - 1; $i > $count - $k; $i--) { //计算数组最后一个元素下标 $this->swap($nums, $i, 0); $heapSize--; $this->maxHeapify($nums, 0, $heapSize); @@ -46,6 +46,7 @@ function maxHeapify(&$arr, $i, $heapSize) if ($r < $heapSize && $arr[$r] > $arr[$max]) { $max = $r; } + //max 代表最大值的下标,有3个位置,自己当前位置,自己的左孩子,自己的右孩子 if ($i != $max) { $this->swap($arr, $i, $max); $this->maxHeapify($arr, $max, $heapSize); From 001358fc84bf4bb45de99c96990207e2983e9a99 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Mon, 25 Jan 2021 18:26:12 +0800 Subject: [PATCH 169/192] =?UTF-8?q?=E9=A2=A0=E5=80=92=E4=BA=8C=E8=BF=9B?= =?UTF-8?q?=E5=88=B6=E4=BD=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week8/190.reverse-bits.php | 39 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Week8/190.reverse-bits.php diff --git a/Week8/190.reverse-bits.php b/Week8/190.reverse-bits.php new file mode 100644 index 00000000..796be2ea --- /dev/null +++ b/Week8/190.reverse-bits.php @@ -0,0 +1,39 @@ + 0) { + $ans += (($n & 1) << $count); + $count--; + $n = ($n >> 1); + } + return $ans; + } + + /** + * 分治 O(1) O(1) + * @param Integer $n + * @return Integer + */ + function reverseBits2($n) + { + $n = (($n & 0x0000FFFF) << 16) | (($n & 0xFFFF0000) >> 16); + $n = (($n & 0x00FF00FF) << 8) | (($n & 0xFF00FF00) >> 8); + $n = (($n & 0x0F0F0F0F) << 4) | (($n & 0xF0F0F0F0) >> 4); + $n = (($n & 0x33333333) << 2) | (($n & 0xCCCCCCCC) >> 2); + $n = (($n & 0x55555555) << 1) | (($n & 0xAAAAAAAA) >> 1); + return $n; + } +} + +$n = 0b1010; +$ret = (new Solution())->reverseBits($n); +print_r(decbin($ret)); From fed056815a274df2dec94cc52348958cfcb1b6ee Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Tue, 23 Feb 2021 13:10:47 +0800 Subject: [PATCH 170/192] =?UTF-8?q?=E8=BD=AC=E6=8D=A2=E6=88=90=E5=B0=8F?= =?UTF-8?q?=E5=86=99=E5=AD=97=E6=AF=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week9/709.to-lower-case.php | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Week9/709.to-lower-case.php diff --git a/Week9/709.to-lower-case.php b/Week9/709.to-lower-case.php new file mode 100644 index 00000000..ce02f67f --- /dev/null +++ b/Week9/709.to-lower-case.php @@ -0,0 +1,30 @@ +toLowerCase($str); +print_r($ret); \ No newline at end of file From 173ad4253d31ca00229af92c923222000fc9fad7 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Tue, 23 Feb 2021 13:20:19 +0800 Subject: [PATCH 171/192] =?UTF-8?q?=E6=9C=80=E5=90=8E=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E5=8D=95=E8=AF=8D=E7=9A=84=E9=95=BF=E5=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week9/58.length-of-last-word.php | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Week9/58.length-of-last-word.php diff --git a/Week9/58.length-of-last-word.php b/Week9/58.length-of-last-word.php new file mode 100644 index 00000000..af4689df --- /dev/null +++ b/Week9/58.length-of-last-word.php @@ -0,0 +1,22 @@ += 0 && $s[$end] == ' ') $end--; + $start = $end; + while ($start >= 0 && $s[$start] != ' ') $start--; + return $end - $start; + } +} + +$s = "Hello World "; +$ret = (new Solution())->lengthOfLastWord($s); +print_r($ret); \ No newline at end of file From bffca4b790394d2b2136b888daeaa50a0c53a714 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 25 Feb 2021 16:30:12 +0800 Subject: [PATCH 172/192] =?UTF-8?q?=E5=AE=9D=E7=9F=B3=E4=B8=8E=E7=9F=B3?= =?UTF-8?q?=E5=A4=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week9/771.jewels-and-stones.php | 35 +++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Week9/771.jewels-and-stones.php diff --git a/Week9/771.jewels-and-stones.php b/Week9/771.jewels-and-stones.php new file mode 100644 index 00000000..17dec4a5 --- /dev/null +++ b/Week9/771.jewels-and-stones.php @@ -0,0 +1,35 @@ +numJewelsInStones($jewels, $stones); +print_r($ret); \ No newline at end of file From 15566e8146463e8d27f1a6bb22e217012dc98f56 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Mon, 17 May 2021 11:11:55 +0800 Subject: [PATCH 173/192] fixed --- Week1/26.remove-duplicates-from-sorted-array.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Week1/26.remove-duplicates-from-sorted-array.php b/Week1/26.remove-duplicates-from-sorted-array.php index 22a7cd2c..306e9c04 100644 --- a/Week1/26.remove-duplicates-from-sorted-array.php +++ b/Week1/26.remove-duplicates-from-sorted-array.php @@ -12,7 +12,7 @@ function removeDuplicates(&$nums) $i = 0; for ($j = 1; $j < count($nums); $j++) { if ($nums[$j] != $nums[$j - 1]) { - $nums[--$i] = $nums[$j]; + $nums[++$i] = $nums[$j]; } } return $i + 1; From 806a02603f6f92768c56545644cbcbeb3ba8606b Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Tue, 18 May 2021 17:19:16 +0800 Subject: [PATCH 174/192] =?UTF-8?q?421.=20=E6=95=B0=E7=BB=84=E4=B8=AD?= =?UTF-8?q?=E4=B8=A4=E4=B8=AA=E6=95=B0=E7=9A=84=E6=9C=80=E5=A4=A7=E5=BC=82?= =?UTF-8?q?=E6=88=96=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...maximum-xor-of-two-numbers-in-an-array.php | 117 ++++++++++++++++++ 1 file changed, 117 insertions(+) create mode 100644 daily/421.maximum-xor-of-two-numbers-in-an-array.php diff --git a/daily/421.maximum-xor-of-two-numbers-in-an-array.php b/daily/421.maximum-xor-of-two-numbers-in-an-array.php new file mode 100644 index 00000000..a6fa2132 --- /dev/null +++ b/daily/421.maximum-xor-of-two-numbers-in-an-array.php @@ -0,0 +1,117 @@ +root = new TrieNode(); + } + + function bulid($num) + { + $node = $this->root; + for ($i = 31; $i >= 0; $i--) { + $bit = ($num >> $i) & 1; + if ($bit) { + if (is_null($node->one)) { + $node->one = new TrieNode(); + } + $node = $node->one; + } else { + if (is_null($node->zero)) { + $node->zero = new TrieNode(); + } + $node = $node->zero; + } + } + } +} + +class Solution +{ + + /** + * @param Integer[] $nums + * @return Integer + */ + function findMaximumXOR($nums) + { + $trie = new Trie(); + foreach ($nums as $num) { + $trie->bulid($num); + } + + $res = PHP_INT_MIN; + foreach ($nums as $num) { + $node = $trie->root; + $tmpVal = 0; + for ($i = 31; $i >= 0; $i--) { + $bit = ($num >> $i) & 1; + if ($bit) { + if (!is_null($node->zero)) { + $node = $node->zero; + $tmpVal += (1 << $i); + } else { + $node = $node->one; + } + } else { + if (!is_null($node->one)) { + $node = $node->one; + $tmpVal += (1 << $i); + } else { + $node = $node->zero; + } + } + } + $res = max($res, $tmpVal); + } + return $res; + } + + /** + * @param Integer[] $nums + * @return Integer + */ + function findMaximumXOR2($nums) { + // 决定每1位能够达到的最大值 + $result = 0; + for ($i = 30; $i >= 0; $i--) { + // 这一位假设取1 + $result = ($result << 1) | 1; + + // 找是否能达到 + $sets = []; + $has = false; + foreach ($nums as $num) { + $temp = $num >> $i; + if (isset($sets[$result ^ $temp])) { + $has = true; + break; + } + $sets[$temp] = true; + } + + if (!$has) { + $result--; + } + } + + return $result; + } +} + +/** + * 输入:nums = [3,10,5,25,2,8] + * 输出:28 + * 解释:最大运算结果是 5 XOR 25 = 28. + */ + +$nums = [3, 10, 5, 25, 2, 8]; +$ret = (new Solution())->findMaximumXOR($nums); +print_r($ret); From 4380700dc82e8887261c6195a6f4a0a5cea28c88 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 19 May 2021 15:59:38 +0800 Subject: [PATCH 175/192] =?UTF-8?q?8.=20=E5=AD=97=E7=AC=A6=E4=B8=B2?= =?UTF-8?q?=E8=BD=AC=E6=8D=A2=E6=95=B4=E6=95=B0=20(atoi)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week9/8.string-to-integer-atoi.php | 72 ++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 Week9/8.string-to-integer-atoi.php diff --git a/Week9/8.string-to-integer-atoi.php b/Week9/8.string-to-integer-atoi.php new file mode 100644 index 00000000..b91b91ed --- /dev/null +++ b/Week9/8.string-to-integer-atoi.php @@ -0,0 +1,72 @@ + ['start', 'signed', 'in_number', 'end'], + 'signed' => ['end', 'end', 'in_number', 'end'], + 'in_number' => ['end', 'end', 'in_number', 'end'], + 'end' => ['end', 'end', 'end', 'end'], + ]; + + public function get($char) + { + //获取当前的状态 + $this->state = $this->table[$this->state][$this->getCol($char)]; + //计算当前的符号 + //print_r($this->state . '|'); + if ($this->state == 'signed') { + $this->sign = ($char == '+') ? 1 : -1; + } + //计算当前的数值 + if ($this->state == 'in_number') { + $this->ans = $this->ans * 10 + $char; + $this->ans = $this->sign == 1 ? min($this->ans, 2 ** 31 - 1) : min($this->ans, 2 ** 31); + } + //print_r($this->ans . PHP_EOL); + } + + /** + * 获取当前字符属于哪一状态 + * @param $char + * @return int + */ + public function getCol($char) + { + if ($char == ' ') { + return 0; + } elseif ($char == '+' | $char == '-') { + return 1; + } elseif (is_numeric($char)) { + return 2; + } else { + return 3; + } + } +} + +class Solution +{ + + /** + * @param String $s + * @return Integer + */ + function myAtoi($s) + { + $auto = new Automation(); + for ($i = 0; $i < strlen($s); $i++) { + $auto->get($s[$i]); + } + return $auto->ans * $auto->sign; + } +} + +$s = '4193 with words'; +$s = ' -42'; +$s = '-91283472332'; //-2147483648 +$ret = (new Solution())->myAtoi($s); +print_r($ret); \ No newline at end of file From e08f9fc6d2690633d2dd252edd0bc351bf564a44 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 19 May 2021 18:38:03 +0800 Subject: [PATCH 176/192] =?UTF-8?q?14.=20=E6=9C=80=E9=95=BF=E5=85=AC?= =?UTF-8?q?=E5=85=B1=E5=89=8D=E7=BC=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week10/14.longest-common-prefix.php | 45 +++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Week10/14.longest-common-prefix.php diff --git a/Week10/14.longest-common-prefix.php b/Week10/14.longest-common-prefix.php new file mode 100644 index 00000000..17b280f3 --- /dev/null +++ b/Week10/14.longest-common-prefix.php @@ -0,0 +1,45 @@ +lcp($prefix, $strs[$i]); + if(empty($prefix)) break; + } + return $prefix; + } + + function lcp($s1, $s2) + { + $minLen = min(strlen($s1), strlen($s2)); + $index = 0; + while ($index < $minLen && $s1[$index] == $s2[$index]) { + $index++; + } + return substr($s1, 0, $index); + } +} + +/** + * + * 输入:strs = ["flower","flow","flight"] + * 输出:"fl" + * 示例 2: + * + * 输入:strs = ["dog","racecar","car"] + * 输出:"" + * 解释:输入不存在公共前缀。 + */ + +$strs = ["flower", "flow", "flight"]; +$ret = (new Solution())->longestCommonPrefix($strs); +print_r($ret); \ No newline at end of file From c504a2aa0e42efce3d9db124fe396e39603839e0 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 19 May 2021 18:51:54 +0800 Subject: [PATCH 177/192] =?UTF-8?q?344.=20=E5=8F=8D=E8=BD=AC=E5=AD=97?= =?UTF-8?q?=E7=AC=A6=E4=B8=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week10/344.reverse-string.php | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Week10/344.reverse-string.php diff --git a/Week10/344.reverse-string.php b/Week10/344.reverse-string.php new file mode 100644 index 00000000..a3aa0c12 --- /dev/null +++ b/Week10/344.reverse-string.php @@ -0,0 +1,33 @@ +reverseString($s); +print_r($ret); \ No newline at end of file From 806819ed78a845e742b1ca35d761cd23a2cfdd4d Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 19 May 2021 19:07:12 +0800 Subject: [PATCH 178/192] =?UTF-8?q?541.=20=E5=8F=8D=E8=BD=AC=E5=AD=97?= =?UTF-8?q?=E7=AC=A6=E4=B8=B2=20II?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week10/541.reverse-string-ii.php | 38 ++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Week10/541.reverse-string-ii.php diff --git a/Week10/541.reverse-string-ii.php b/Week10/541.reverse-string-ii.php new file mode 100644 index 00000000..bfe93e15 --- /dev/null +++ b/Week10/541.reverse-string-ii.php @@ -0,0 +1,38 @@ +reverseStr($s, $k); +print_r($ret); \ No newline at end of file From bc4278c06a00896be391a6998e40893cb493b08f Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 20 May 2021 16:48:28 +0800 Subject: [PATCH 179/192] =?UTF-8?q?151.=20=E7=BF=BB=E8=BD=AC=E5=AD=97?= =?UTF-8?q?=E7=AC=A6=E4=B8=B2=E9=87=8C=E7=9A=84=E5=8D=95=E8=AF=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week10/151.reverse-words-in-a-string.php | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Week10/151.reverse-words-in-a-string.php diff --git a/Week10/151.reverse-words-in-a-string.php b/Week10/151.reverse-words-in-a-string.php new file mode 100644 index 00000000..e01c9010 --- /dev/null +++ b/Week10/151.reverse-words-in-a-string.php @@ -0,0 +1,23 @@ +reverseWords($s); +print_r($ret); \ No newline at end of file From f00da97a31120509cff9f42fcef7eb1126b01b75 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 20 May 2021 17:15:22 +0800 Subject: [PATCH 180/192] =?UTF-8?q?557.=20=E5=8F=8D=E8=BD=AC=E5=AD=97?= =?UTF-8?q?=E7=AC=A6=E4=B8=B2=E4=B8=AD=E7=9A=84=E5=8D=95=E8=AF=8D=20III?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week10/557.reverse-words-in-a-string-iii.php | 26 ++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Week10/557.reverse-words-in-a-string-iii.php diff --git a/Week10/557.reverse-words-in-a-string-iii.php b/Week10/557.reverse-words-in-a-string-iii.php new file mode 100644 index 00000000..bf70e4cf --- /dev/null +++ b/Week10/557.reverse-words-in-a-string-iii.php @@ -0,0 +1,26 @@ +reverseWords($s); +print_r($ret); \ No newline at end of file From d42fcb61cc4a2f6f075948f69be016c1c9199b03 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 20 May 2021 17:44:20 +0800 Subject: [PATCH 181/192] =?UTF-8?q?917.=20=E4=BB=85=E4=BB=85=E5=8F=8D?= =?UTF-8?q?=E8=BD=AC=E5=AD=97=E6=AF=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week10/917.reverse-only-letters.php | 48 +++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Week10/917.reverse-only-letters.php diff --git a/Week10/917.reverse-only-letters.php b/Week10/917.reverse-only-letters.php new file mode 100644 index 00000000..5edc2143 --- /dev/null +++ b/Week10/917.reverse-only-letters.php @@ -0,0 +1,48 @@ +isChar($s[$i])) { + $stack->push($s[$i]); + } + } + $ans = ''; + for ($i = 0; $i < strlen($s); $i++) { + if ($this->isChar($s[$i])) { + $ans .= $stack->pop(); + }else{ + $ans .= $s[$i]; + } + } + return $ans; + } + + function isChar($char) + { + $ord = ord($char); + return ($ord >= 65 && $ord <= 90) || ($ord >= 97 && $ord <= 122); + } +} + +/** + * 输入:"a-bC-dEf-ghIj" + * 输出:"j-Ih-gfE-dCba" + * + * 输入:"Test1ng-Leet=code-Q!" + * 输出:"Qedo1ct-eeLg=ntse-T!" + */ + +$s = 'a-bC-dEf-ghIj'; +$ret = (new Solution())->reverseOnlyLetters($s); +print_r($ret); \ No newline at end of file From f0f437b83e3f7b91cd659b0536e322273032b40b Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Fri, 21 May 2021 16:14:23 +0800 Subject: [PATCH 182/192] =?UTF-8?q?438.=20=E6=89=BE=E5=88=B0=E5=AD=97?= =?UTF-8?q?=E7=AC=A6=E4=B8=B2=E4=B8=AD=E6=89=80=E6=9C=89=E5=AD=97=E6=AF=8D?= =?UTF-8?q?=E5=BC=82=E4=BD=8D=E8=AF=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week10/438.find-all-anagrams-in-a-string.php | 64 ++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 Week10/438.find-all-anagrams-in-a-string.php diff --git a/Week10/438.find-all-anagrams-in-a-string.php b/Week10/438.find-all-anagrams-in-a-string.php new file mode 100644 index 00000000..4c8cf1e2 --- /dev/null +++ b/Week10/438.find-all-anagrams-in-a-string.php @@ -0,0 +1,64 @@ + $need[$curR]) { + $curL = ord($s[$left]) - ord('a'); + $left++; + $widow[$curL]--; + } + //如果窗口内元素个数刚好与p个数相等 那么当前窗口内元素肯定是异位词 因为上一步保证了窗口内元素出现的次数肯定是符合的 + //当元素的频次与个数都相等肯定是异位词 + if ($right - $left == $lenP) { + $ans[] = $left; + } + } + return $ans; + } +} + +/** + * 输入: + * s: "cbaebabacd" p: "abc" + * 输出: + * [0, 6] + * 解释: + * 起始索引等于 0 的子串是 "cba", 它是 "abc" 的字母异位词。 + * 起始索引等于 6 的子串是 "bac", 它是 "abc" 的字母异位词。 + */ + +$s = 'cbaebabacd'; +$p = 'abc'; +$ret = (new Solution())->findAnagrams($s,$p); +print_r($ret); \ No newline at end of file From 6e2974c23eeb2581690b3e50dd2ce8353a9a6a9b Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Fri, 21 May 2021 18:24:52 +0800 Subject: [PATCH 183/192] =?UTF-8?q?125.=20=E9=AA=8C=E8=AF=81=E5=9B=9E?= =?UTF-8?q?=E6=96=87=E4=B8=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week10/125.valid-palindrome.php | 55 +++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Week10/125.valid-palindrome.php diff --git a/Week10/125.valid-palindrome.php b/Week10/125.valid-palindrome.php new file mode 100644 index 00000000..9fcfb0fa --- /dev/null +++ b/Week10/125.valid-palindrome.php @@ -0,0 +1,55 @@ +isalnum($s[$left])) $left++; + while ($left < $right && !$this->isalnum($s[$right])) $right--; + if ($left < $right) { + if (strtolower($s[$left]) != strtolower($s[$right]) && $left != $right) { + return false; + } + $left++; + $right--; + } + } + return true; + } + + /** + * a-z 97-122 + * A-Z 65-90 + * 0-9 48-57 + * @param $char + */ + function isalnum($char) + { + $ord = ord($char); + return ($ord >= 65 && $ord <= 90) || ($ord >= 97 && $ord <= 122) || ($ord >= 48 && $ord <= 57); + } +} + +$s = 'A man, a plan, a canal: Panama'; +$ret = (new Solution())->isPalindrome($s); +var_dump($ret); + +/** + * + * 输入: "A man, a plan, a canal: Panama" + * 输出: true + * + * 输入: "race a car" + * 输出: false + * + */ \ No newline at end of file From 5c101be09e22a65e1478180b2c4b953480b3e436 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Fri, 21 May 2021 19:13:26 +0800 Subject: [PATCH 184/192] =?UTF-8?q?680.=20=E9=AA=8C=E8=AF=81=E5=9B=9E?= =?UTF-8?q?=E6=96=87=E5=AD=97=E7=AC=A6=E4=B8=B2=20=E2=85=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week10/680.valid-palindrome-ii.php | 49 ++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Week10/680.valid-palindrome-ii.php diff --git a/Week10/680.valid-palindrome-ii.php b/Week10/680.valid-palindrome-ii.php new file mode 100644 index 00000000..7aaf2520 --- /dev/null +++ b/Week10/680.valid-palindrome-ii.php @@ -0,0 +1,49 @@ +isPalindrome($s, $left + 1, $right) || $this->isPalindrome($s, $left, $right - 1); + } + } + return true; + } + + function isPalindrome($s, $low, $high) + { + while ($low < $high) { + if ($s[$low] != $s[$high] && $low != $high) return false; + $low++; + $high--; + } + return true; + } +} + +/** + * 输入: "aba" + * 输出: True + * + * 输入: "abca" + * 输出: True + * 解释: 你可以删除c字符。 + */ + +$s = 'abca'; +$ret = (new Solution())->validPalindrome($s); +var_dump($ret); \ No newline at end of file From dab418942ef35f592960ac652bb092701d110ce6 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sun, 30 May 2021 16:15:10 +0800 Subject: [PATCH 185/192] =?UTF-8?q?=E6=9C=80=E9=95=BF=E5=9B=9E=E6=96=87?= =?UTF-8?q?=E5=AD=90=E4=B8=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week10/5.longest-palindromic-substring.php | 57 ++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Week10/5.longest-palindromic-substring.php diff --git a/Week10/5.longest-palindromic-substring.php b/Week10/5.longest-palindromic-substring.php new file mode 100644 index 00000000..34983a11 --- /dev/null +++ b/Week10/5.longest-palindromic-substring.php @@ -0,0 +1,57 @@ += $len) break; //右边界取不到$len的所以是>= + + if ($s[$j] == $s[$end]) { + if ($end - $j < 3) { + $dp[$j][$end] = true; + } else { + $dp[$j][$end] = $dp[$j + 1][$end - 1]; + } + } else { + $dp[$j][$end] = false; + } + + if ($dp[$j][$end] && ($end - $j + 1) > $maxLen) { + $maxLen = $end - $j + 1; + $begin = $j; + } + } + } + + return substr($s, $begin, $maxLen); + } +} + +/** + * 输入:s = "babad" + * 输出:"bab" + * 解释:"aba" 同样是符合题意的答案。 + */ +$s = "babad"; +$s = "bb"; +$ret = (new Solution())->longestPalindrome($s); +print_r($ret); \ No newline at end of file From 0b2855a7c73a01bfaf535b52022cb61aedeaced9 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Sun, 30 May 2021 16:16:48 +0800 Subject: [PATCH 186/192] add comment --- Week10/5.longest-palindromic-substring.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Week10/5.longest-palindromic-substring.php b/Week10/5.longest-palindromic-substring.php index 34983a11..df9c713c 100644 --- a/Week10/5.longest-palindromic-substring.php +++ b/Week10/5.longest-palindromic-substring.php @@ -26,7 +26,7 @@ function longestPalindrome($s) if ($end >= $len) break; //右边界取不到$len的所以是>= if ($s[$j] == $s[$end]) { - if ($end - $j < 3) { + if ($end - $j < 3) { //相等的两个字符串都是回文串 $dp[$j][$end] = true; } else { $dp[$j][$end] = $dp[$j + 1][$end - 1]; From 9b124dd4bff7d5be7c4c47838ee585f9938d047e Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Mon, 31 May 2021 19:21:51 +0800 Subject: [PATCH 187/192] =?UTF-8?q?=E6=9C=80=E7=9F=AD=E7=BC=96=E8=BE=91?= =?UTF-8?q?=E8=B7=9D=E7=A6=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week10/72.edit-distance.php | 82 +++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 Week10/72.edit-distance.php diff --git a/Week10/72.edit-distance.php b/Week10/72.edit-distance.php new file mode 100644 index 00000000..bf5751f4 --- /dev/null +++ b/Week10/72.edit-distance.php @@ -0,0 +1,82 @@ + rorse (将 'h' 替换为 'r') + * rorse -> rose (删除 'r') + * rose -> ros (删除 'e') + */ +$word1 = "horse"; +$word2 = "ros"; +$ret = (new Solution())->minDistance($word1, $word2); +print_r($ret); \ No newline at end of file From 25b27c87ffb5770091f5b5d77230ccac983c6065 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Tue, 1 Jun 2021 20:02:20 +0800 Subject: [PATCH 188/192] =?UTF-8?q?=E6=AD=A3=E5=88=99=E8=A1=A8=E8=BE=BE?= =?UTF-8?q?=E5=BC=8F=E5=8C=B9=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week10/10.regular-expression-matching.php | 70 +++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 Week10/10.regular-expression-matching.php diff --git a/Week10/10.regular-expression-matching.php b/Week10/10.regular-expression-matching.php new file mode 100644 index 00000000..9c46dc68 --- /dev/null +++ b/Week10/10.regular-expression-matching.php @@ -0,0 +1,70 @@ +isMatch($s, $p); +var_dump($ret); \ No newline at end of file From 893c101706960dd45c38e8be489a6b21a9f9c2e2 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 2 Jun 2021 16:31:51 +0800 Subject: [PATCH 189/192] add comment --- Week10/10.regular-expression-matching.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Week10/10.regular-expression-matching.php b/Week10/10.regular-expression-matching.php index 9c46dc68..b1a64e96 100644 --- a/Week10/10.regular-expression-matching.php +++ b/Week10/10.regular-expression-matching.php @@ -30,6 +30,10 @@ function isMatch($s, $p) $dp[$i][$j] = $dp[$i][$j - 2]; } else { //否则就是相等,只需判断前面是否匹配 +// dp[i][j] = dp[i-1][j] // * 匹配了 多个字符 +// or dp[i][j] = dp[i][j-1] // * 匹配了 单个字符 +// or dp[i][j] = dp[i][j-2] // * 没有匹配 字符 + $dp[$i][$j] = $dp[$i - 1][$j] || $dp[$i][$j - 1] || $dp[$i][$j - 2]; } } From ccb8763aa44a10a8fc0ac495a4b66b31bb7b1300 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Wed, 2 Jun 2021 16:32:12 +0800 Subject: [PATCH 190/192] =?UTF-8?q?44.=20=E9=80=9A=E9=85=8D=E7=AC=A6?= =?UTF-8?q?=E5=8C=B9=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week10/44.wildcard-matching.php | 80 +++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 Week10/44.wildcard-matching.php diff --git a/Week10/44.wildcard-matching.php b/Week10/44.wildcard-matching.php new file mode 100644 index 00000000..ee42a24f --- /dev/null +++ b/Week10/44.wildcard-matching.php @@ -0,0 +1,80 @@ +isMatch($s, $p); +var_dump($ret); \ No newline at end of file From ddbbfe48303386461891f7c32453407951af8001 Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 3 Jun 2021 18:46:16 +0800 Subject: [PATCH 191/192] =?UTF-8?q?115.=20=E4=B8=8D=E5=90=8C=E7=9A=84?= =?UTF-8?q?=E5=AD=90=E5=BA=8F=E5=88=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week10/115.distinct-subsequences.php | 95 ++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 Week10/115.distinct-subsequences.php diff --git a/Week10/115.distinct-subsequences.php b/Week10/115.distinct-subsequences.php new file mode 100644 index 00000000..560412dd --- /dev/null +++ b/Week10/115.distinct-subsequences.php @@ -0,0 +1,95 @@ +numDistinct($s, $t); +print_r($ret); \ No newline at end of file From 9012d501b6aa2d136d08c30ddf4f201018a25b4b Mon Sep 17 00:00:00 2001 From: wangyoukun <1171725650@qq.com> Date: Thu, 17 Jun 2021 15:16:24 +0800 Subject: [PATCH 192/192] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E6=9C=80=E5=B0=8F?= =?UTF-8?q?=E7=BC=96=E8=BE=91=E8=B7=9D=E7=A6=BB=E6=9C=B1=E5=A7=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week10/72.edit-distance.php | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/Week10/72.edit-distance.php b/Week10/72.edit-distance.php index bf5751f4..80fe3d59 100644 --- a/Week10/72.edit-distance.php +++ b/Week10/72.edit-distance.php @@ -13,6 +13,25 @@ class Solution * demo:'horse' 'ros'; 'intention' 'execution'; 'zoologicoarchaeologist' 'zoogeologist'; */ /* + D[i][j-1] 为 A 的前 i 个字符和 B 的前 j - 1 个字符编辑距离的子问题。 + 即对于 B 的第 j 个字符,我们在 A 的末尾添加了一个相同的字符,那么 D[i][j] 最小可以为 D[i][j-1] + 1; + + D[i-1][j] 为 A 的前 i - 1 个字符和 B 的前 j 个字符编辑距离的子问题。 + 即对于 A 的第 i 个字符,我们在 B 的末尾添加了一个相同的字符,那么 D[i][j] 最小可以为 D[i-1][j] + 1; + + D[i-1][j-1] 为 A 前 i - 1 个字符和 B 的前 j - 1 个字符编辑距离的子问题。 + 即对于 B 的第 j 个字符,我们修改 A 的第 i 个字符使它们相同,那么 D[i][j] 最小可以为 D[i-1][j-1] + 1。 + 特别地,如果 A 的第 i 个字符和 B 的第 j 个字符原本就相同,那么我们实际上不需要进行修改操作。 + 在这种情况下,D[i][j] 最小可以为 D[i-1][j-1]。 + + 那么我们可以写出如下的状态转移方程: + + 若 A 和 B 的最后一个字母相同: + D[i][j]=min(D[i][j−1]+1,D[i−1][j]+1,D[i−1][j−1]) + =1+min(D[i][j−1],D[i−1][j],D[i−1][j−1]−1) + 若 A 和 B 的最后一个字母不同: + D[i][j]=1+min(D[i][j−1],D[i−1][j],D[i−1][j−1]) + (一)、当word1[i] == word2[j]时,由于遍历到了i和j,说明word1的0~i-1和word2的0~j-1的匹配结果已经生成, 由于当前两个字符相同,因此无需做任何操作,dp[i][j] = dp[i-1][j-1]