题目
给你两个长度为 n
下标从 0
开始的整数数组 cost
和 time
,分别表示给 n
堵不同的墙刷油漆需要的开销和时间。你有两名油漆匠:
- 一位需要付费的油漆匠,刷第
i
堵墙需要花费time[i]
单位的时间,开销为cost[i]
单位的钱。 - 一位免费的油漆匠,刷任意一堵墙的时间为
1
单位,开销为0
。但是必须在付费油漆匠工作时,免费油漆匠才会工作。
请你返回刷完 n
堵墙最少开销为多少。
示例 1:
输入:cost = [1, 2, 3, 2]
, time = [1, 2, 3, 2]
输出:3
解释:下标为 0
和 1
的墙由付费油漆匠来刷,需要 3
单位时间。同时,免费油漆匠刷下标为 2
和 3
的墙,需要 2
单位时间,开销为 0
。总开销为 1 + 2 = 3
。
示例 2:
输入:cost = [2, 3, 4, 2]
, time = [1, 1, 1, 1]
输出:4
解释:下标为 0
和 3
的墙由付费油漆匠来刷,需要 2
单位时间。同时,免费油漆匠刷下标为 1
和 2
的墙,需要 2
单位时间,开销为 0
。总开销为 2 + 2 = 4
。
提示:
1 <= cost.length <= 500
cost.length == time.length
1 <= cost[i] <= 10^6
1 <= time[i] <= 500
代码
完整代码
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <stdbool.h>
typedef struct {
int cost;
int time;
bool free; // 初始化为全部付费
} walls_t;
void dfs(walls_t *wall, int indexToPaint, bool free, int n, int* totalCost) {
if (indexToPaint >= n) {
return;
}
wall[indexToPaint].free = free;
int totalCanPaint = 0;
int nowCost = 0;
for (int i = 0; i < n; i++) {
totalCanPaint += (!wall[i].free) ? wall[i].time + 1 : 0;
if (totalCanPaint >= n) {
break;
}
}
if (totalCanPaint >= n) {
for (int i = 0; i < n; i++) {
nowCost += (!wall[i].free) ? wall[i].cost : 0;
}
if (nowCost < (*totalCost)) {
(*totalCost) = nowCost;
}
}
dfs(wall, indexToPaint + 1, false, n, totalCost);
dfs(wall, indexToPaint + 1, true, n, totalCost);
}
int paintWalls(int* cost, int costSize, int* time, int timeSize) {
int n = costSize;
int totalCost = INT_MAX;
walls_t* wall = (walls_t*)calloc(n, sizeof(walls_t));
for (int i = 0; i < n; i++) {
wall[i].cost = cost[i];
wall[i].time = time[i];
}
dfs(wall, 0, false, n, &totalCost);
dfs(wall, 0, true, n, &totalCost);
free(wall);
return totalCost;
}
思路分析
这套代码用了深度优先搜索(DFS)的方法。
代码的整体逻辑是:
- 使用一个结构体数组
wall
来保存每堵墙的费用、时间和是否免费。 - 通过递归遍历所有可能的涂墙组合,分别考虑当前墙由付费油漆匠或免费油漆匠涂刷。
- 在每种组合下,计算总涂墙时间和费用,并更新最小费用。
- 最终返回最小的总开销。
拆解分析
- dfs函数
void dfs(walls_t *wall, int indexToPaint, bool free, int n, int* totalCost) {
if (indexToPaint >= n) {
return;
}
wall[indexToPaint].free = free;
int totalCanPaint = 0;
int nowCost = 0;
for (int i = 0; i < n; i++) {
totalCanPaint += (!wall[i].free) ? wall[i].time + 1 : 0;
if (totalCanPaint >= n) {
break;
}
}
if (totalCanPaint >= n) {
for (int i = 0; i < n; i++) {
nowCost += (!wall[i].free) ? wall[i].cost : 0;
}
if (nowCost < (*totalCost)) {
(*totalCost) = nowCost;
}
}
dfs(wall, indexToPaint + 1, false, n, totalCost);
dfs(wall, indexToPaint + 1, true, n, totalCost);
}
这个函数是递归实现的核心,用于深度优先遍历所有可能的涂墙组合。
- 主函数paintWalls
int paintWalls(int* cost, int costSize, int* time, int timeSize) {
int n = costSize;
int totalCost = INT_MAX;
walls_t* wall = (walls_t*)calloc(n, sizeof(walls_t));
for (int i = 0; i < n; i++) {
wall[i].cost = cost[i];
wall[i].time = time[i];
}
dfs(wall, 0, false, n, &totalCost);
dfs(wall, 0, true, n, &totalCost);
free(wall);
return totalCost;
}
这个函数初始化数据结构,调用 dfs
函数进行递归,并返回最终的最小费用。
复杂度分析
- 时间复杂度:DFS 的时间复杂度是 O(2^n),因为每堵墙有两种选择(付费或免费)。
- 空间复杂度:主要是递归栈和结构体数组的空间,空间复杂度为 O(n)。