做了一下Google的切木头# JobHunting - 待字闺中
w*x
1 楼
//least cost to cut a batten
//the cost of cutting each segment is the cost of the segment length, an
array is storing each end point, eg:
// [0, 3, 7, 8, 11, 12], the batten length is 12, there are 4 cuting point
//No greedy solution to this problem
int getMinCost(int a[], int n)
{
if (NULL == a || n <= 1)
return -1;
int rec[100][100] = {0};
for (int i = 2; i < n; i++)
{
for (int j = 0; j < n-i; j++)
{
int nMin = INT_MAX;
for (int k = 1; k < i; k++)
nMin = min(nMin, rec[j][j+k] + rec[j+k][j+i] + a[j+i] - a[j]
);
rec[j][j+i] = nMin;
}
}
return rec[0][n-1];
}
代码不长, 很容易出错, 这几行code出了3个错
//the cost of cutting each segment is the cost of the segment length, an
array is storing each end point, eg:
// [0, 3, 7, 8, 11, 12], the batten length is 12, there are 4 cuting point
//No greedy solution to this problem
int getMinCost(int a[], int n)
{
if (NULL == a || n <= 1)
return -1;
int rec[100][100] = {0};
for (int i = 2; i < n; i++)
{
for (int j = 0; j < n-i; j++)
{
int nMin = INT_MAX;
for (int k = 1; k < i; k++)
nMin = min(nMin, rec[j][j+k] + rec[j+k][j+i] + a[j+i] - a[j]
);
rec[j][j+i] = nMin;
}
}
return rec[0][n-1];
}
代码不长, 很容易出错, 这几行code出了3个错