算法题-深度优先搜索(DFS)

题目见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);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值