leetcode-134. 加油站

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
int n = 0;
int pre = 0;
public int canCompleteCircuit(int[] gas, int[] cost) {
n = gas.length;
for (int i = 0; i < n; i++) {
pre = i;
if (dfs(gas, cost, i, gas[i])) {
return i;
}
}
return -1;
}

public boolean dfs(int[] gas, int[] cost, int cur , int totalGas) {
if (totalGas < cost[cur]) {
return false;
}

if ((cur+1) % n == pre && totalGas >= cost[cur]){
return true;
}

for (int i = cur; i < n; i++) {
int idx = (cur + 1) % n;
return dfs(gas, cost, (i+1) % n, totalGas - cost[cur] + gas[idx]);
}
return false;
}
}