题目见leetcode 403题
解法一:深度优先搜索
深度优先搜索尝试所有的方案,直到找到答案为止。时间复杂度高,超时。
class Solution{
private:
set<int>stonesSet;
bool dfs(vector<int>& stones, int stoneNum, int lastDist){
if(stoneNum = stones[stones.size()-1]) return true;
for(int step = lastDist - 1; step<=lastDist; step++){
if(step> 0 && stonesSet.count(stoneNum + step)){
if(dfs(stones, stoneNum + step, step)){
return true;
}
}
}
return false;
}
public:
bool canCross(vector<int>& stones){
stonesSet = set<int>(stones.begin(), stones.end());
return dfs(stones, stones[0], 0);
}
}
时间复杂度优化
记忆化搜索
class Solution{
private:
vector<map<int, bool>> rec;
bool dfs(vector<int>& stones, int i, int step){
if(i == stones.size()-1) return true;
if(rec[i].count(step)){
return rec[i][step];
}
for(int cstep = step - 1; cstep <= step+1; cstep++){
if(cstep > 0){
auto it = lower_bound(stones.begin(), stone.end(), stones[i]+cstep);
if(it != stones.end()){
int j = it - stones.begin();
if(stones[j] == stones[i] + cstep && dfs(stones, j, cstep)){
return rec[j][stones[i] + cstep] = true;
}
}
}
}
return rec[i][step] = false;
}
public:
bool canCross(vector<int>& stones){
rec.resize(stones.size() - 1);
return dfs(stones, 0, 0);
}
}