1. 程式人生 > 實用技巧 >leetcode 統計所有可行路徑

leetcode 統計所有可行路徑

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;
    }
};