funcvideoStitching(clips [][]int, time int)int { const inf = math.MaxInt64 - 1 dp := make([]int, time+1) for i := range dp { dp[i] = inf } dp[0] = 0 for i := 1; i <= time; i++ { for _, c := range clips { l, r := c[0], c[1] // 若能剪出子区间 [l,i],则可以从 dp[l] 转移到 dp[i] if l < i && i <= r && dp[l]+1 < dp[i] { dp[i] = dp[l] + 1 } } } if dp[time] == inf { return-1 } return dp[time] }
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12 13
intvideoStitching(int** clips, int clipsSize, int* clipsColSize, int time) { int dp[time + 1]; memset(dp, 0x3f, sizeof(dp)); dp[0] = 0; for (int i = 1; i <= time; i++) { for (int j = 0; j < clipsSize; j++) { if (clips[j][0] < i && i <= clips[j][1]) { dp[i] = fmin(dp[i], dp[clips[j][0]] + 1); } } } return dp[time] == 0x3f3f3f3f ? -1 : dp[time]; }
[sol1-Python3]
1 2 3 4 5 6 7 8 9
classSolution: defvideoStitching(self, clips: List[List[int]], time: int) -> int: dp = [0] + [float("inf")] * time for i inrange(1, time + 1): for aj, bj in clips: if aj < i <= bj: dp[i] = min(dp[i], dp[aj] + 1) return -1if dp[time] == float("inf") else dp[time]
同时我们还需要记录上一个被使用的子区间的结束位置为 pre,每次我们越过一个被使用的子区间,就说明我们要启用一个新子区间,这个新子区间的结束位置即为当前的 last。也就是说,每次我们遇到 i == \textit{pre,则说明我们用完了一个被使用的子区间。这种情况下我们让答案加 1,并更新 pre 即可。
classSolution { public: intvideoStitching(vector<vector<int>>& clips, int time){ vector<int> maxn(time); int last = 0, ret = 0, pre = 0; for (vector<int>& it : clips) { if (it[0] < time) { maxn[it[0]] = max(maxn[it[0]], it[1]); } } for (int i = 0; i < time; i++) { last = max(last, maxn[i]); if (i == last) { return-1; } if (i == pre) { ret++; pre = last; } } return ret; } };
funcvideoStitching(clips [][]int, time int) (ans int) { maxn := make([]int, time) last, pre := 0, 0 for _, c := range clips { l, r := c[0], c[1] if l < time && r > maxn[l] { maxn[l] = r } } for i, v := range maxn { if v > last { last = v } if i == last { return-1 } if i == pre { ans++ pre = last } } return }
intvideoStitching(int** clips, int clipsSize, int* clipsColSize, int time) { int maxn[time + 1]; memset(maxn, 0, sizeof(maxn)); int last = 0, ret = 0, pre = 0; for (int i = 0; i < clipsSize; i++) { if (clips[i][0] < time) { maxn[clips[i][0]] = fmax(maxn[clips[i][0]], clips[i][1]); } } for (int i = 0; i < time; i++) { last = fmax(last, maxn[i]); if (i == last) { return-1; } if (i == pre) { ret++; pre = last; } } return ret; }
[sol2-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution: defvideoStitching(self, clips: List[List[int]], time: int) -> int: maxn = [0] * time last = ret = pre = 0 for a, b in clips: if a < time: maxn[a] = max(maxn[a], b) for i inrange(time): last = max(last, maxn[i]) if i == last: return -1 if i == pre: ret += 1 pre = last return ret