https://www.lintcode.com/problem/order-problem/description
public class Solution {
private int result = Integer.MAX_VALUE;
/**
* @param order: The order
* @param pattern: The pattern
* @return: Return the number of items do not meet the demand at least
*/
public int getMinRemaining(int[] order, int[][] pattern) {
// Write your code here
treeWalk(order, 0, pattern);
return result;
}
private void treeWalk(int[] order, int index, int[][] pattern) {
int[] pat = pattern[index];
int max = Integer.MAX_VALUE;
for (int i = 0; i < order.length; i++) {
if (pat[i] != 0) {
max = Math.min(max, order[i] / pat[i]);
}
}
if (max == Integer.MAX_VALUE) {
max = 0;
}
if (index == pattern.length - 1) {
int temp = 0;
for (int i = 0; i < pat.length; i++) {
temp += order[i] - pat[i] * max;
}
result = Math.min(temp, result);
return;
}
for (int i = 0; i <= max; i++) {
if (i > 0) {
for (int j = 0; j < order.length; j++) {
order[j] -= pat[j] * i;
}
}
treeWalk(order, index + 1, pattern);
if (i > 0) {
for (int j = 0; j < order.length; j++) {
order[j] += pat[j] * i;
}
}
}
}
}
网友评论