class Solution {
//利用bfs来进行遍历
public int coinChange(int[] coins, int amount) {
Deque<int[] > queue = new LinkedList();
boolean[] vst = new boolean[amount + 1];
//初始化
vst[0] = true;
queue.addLast(new int[]{0,0}); // {a,b} a已凑金额,b当前步长
while(!queue.isEmpty()){
int[] arr = queue.pollFirst();
int node = arr[0], w = arr[1];
if(node == amount) return w;
for(int coin : coins){
//代码出错的地方
if((coin + node) > amount || vst[coin + node]) continue;
queue.addLast(new int[]{coin + node, w + 1});
vst[coin + node] = true;
}
}
return -1;
}
}
如果代码修改
if(coin > amount - node || vst[coin + node]) continue;
就会导致在特殊的情况下出现索引越界,这种特殊情况是由于int的最大值限制导致的
即
node为1时,coin为2147483647(即int的最大值),此时再加1,就会等于-2147483648,就会前面的判断错误,也会导致后面的数组索引越界。
所以之后在写判断时,能减则不加!