中级农民
- 积分
- 124
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2013-2-20
- 最后登录
- 1970-1-1
|
public int minCostII(int[][] costs){
if(costs == null || costs.length == 0 || costs[0].length <= 1){
return 0;
}
int k = costs.length;
int n = costs[0].length;
int firstIndex = -1;
int first = 0;
int second = 0;
for(int i=1;i<n;i++){
int newFirst = Integer.MAX_VALUE;
int newSecond = Integer.MAX_VALUE;
int newFirstIndex = -1;
for(int j=0;j<k;j++){
int cur = costs[j][i];
costs[j][i] = cur + (firstIndex == j? second:first);
if(costs[j][i] < newFirst){
newSecond = newFirst;
newFirst = costs[j][i];
newFirstIndex = j;
}
else if(costs[j][i] < newSecond){
newSecond = costs[j][i];
}
}
first = newFirst;
firstIndex = newFirstIndex;
second = newSecond;
}
return first;
}
写了一个,因为没有买premium,所以不知道能不能AC,只是提供一下自己的思路,也不知道对不对,求讨论。
用DP,如果不能改变costs[][]的值,就新create一个matrix,cost[j][i]表示第i个房子刷第k种颜色,前i个房子最少的cost,记录firstIndex是为了满足相邻房子不能刷同种颜色的条件。
可能会有bug, |
|