https://leetcode-cn.com/problems/count-all-possible-routes/
dp[x][y]从x到终点,使用y的油。
具体看注释
#include<iostream> #include<algorithm> #include<cstring> #include<vector> using namespace std; typedef long long ll; ll inf = -1e16; const int maxn = 220; ll mod = 1e9+7; ll dp[maxn][maxn]; ll lst[maxn]; int n,en; ll ans = 0; ll dfs(int x,int val){ if(dp[x][val] != -1) return dp[x][val]; ll cns = 0; if(x == en) cns = 1;//证明有一种新的到达en的方法 for(int i=1;i<=n;i++){ int len = abs(lst[i] - lst[x]); if(len == 0) continue; if(len <= val){ cns = (cns + dfs(i,val - len))%mod; } } return dp[x][val] = cns; } class Solution { public: int countRoutes(vector<int>& locations, int be, int endd, int val) { n = locations.size(); be++,endd++; en = endd; for(int i=0;i<=n;i++){ for(int j=0;j<maxn;j++){ dp[i][j] = -1; } } for(int i=1;i<=n;i++){ lst[i] = locations[i-1]; } ll ans = dfs(be,val)%mod; return ans; } };