1
/** https://leetcode.com/problems/video-stitching/2
* @param {number[][]} clips6
var videoStitching = function (clips, time) {10
// Sort the clips for easier iteration11
clips.sort((a, b) => a[0] - b[0]);13
// If the output is `Infinity` it means the task is impossible14
let out = dp(clips, time, 0, -1);15
return out === Infinity ? -1 : out;18
var dp = function (clips, time, index, endTime) {19
let key = `${index}_${endTime}`;21
// Base, we got all the clip we need22
if (endTime >= time) {26
// Reach end of the clip array27
if (index === clips.length) {32
if (this.memo.has(key) === true) {33
return this.memo.get(key);36
// There are 2 choices, include clip in current `index` or exclude37
// Include clip in current `index`38
let include = Infinity;40
// We can only include clip in current `index` if either:41
// - the `endTime` is -1 and current clip's starting is 0, in which this clip is the first segment42
// - the `endTime` is greater than current clip's starting time, in which this clip has end time greater than our `endTime`43
if ((endTime < 0 && clips[index][0] === 0) || endTime >= clips[index][0]) {44
// Update the next `endTime` with the current clip's end time, `clips[index][1]`45
let nextEndTime = clips[index][1];46
include = 1 + dp(clips, time, index + 1, nextEndTime);49
// Exclude clip in current `index`50
let exclude = dp(clips, time, index + 1, endTime);52
// Find which one has less clips53
let count = Math.min(include, exclude);56
this.memo.set(key, count);