https://leetcode-cn.com/problems/chuan-di-xin-xi/
思路一:无脑遍历,dfs/bfs均可,时间复杂度
O
(
n
k
)
O(n^k)
O(nk)。
class Solution {
public:
int numWays(int n, vector<vector<int>>& relation, int k) {
vector<vector<int>> vec(n,vector<int>());
for(vector<int>& rel:relation)
vec[rel[0]].push_back(rel[1]);
using pr=pair<int,int>;
queue<pr> q;
q.emplace(0,0);
int ans=0;
while(!q.empty())
{
pr f=q.front();
q.pop();
if(f.second<k)
{
for(int to:vec[f.first])
q.emplace(to,f.second+1);
}
else if(f.second==k&&f.first==n-1)
++ans;
}
return ans;
}
};
思路二:
d
p
i
,
j
dp_{i,j}
dpi,j表示经过
j
j
j次传递后达到点
i
i
i的情况数,初始化
d
p
0
,
0
=
1
dp_{0,0}=1
dp0,0=1,有转移方程:
d
p
j
,
k
=
∑
i
=
0
n
−
1
∑
j
(
i
,
j
)
∈
E
d
p
j
,
k
−
1
dp_{j,k}=\sum_{i=0}^{n-1}\sum_j^{(i,j)\in E}dp_{j,k-1}
dpj,k=i=0∑n−1j∑(i,j)∈Edpj,k−1
时间复杂度可降低至 O ( m k ) O(mk) O(mk),其中 m m m为边的总数。
class Solution {
public:
int numWays(int n, vector<vector<int>>& relation, int k) {
vector<vector<int>> vec(n,vector<int>());
vector<vector<int>> dp(n,vector<int>(k+1,0));
for(vector<int>& rel:relation)
vec[rel[0]].push_back(rel[1]);
dp[0][0]=1;
for(int times=1;times<=k;times++)
{
for(int i=0;i<n;i++)
{
for(int to:vec[i])
dp[to][times]+=dp[i][times-1];
}
}
return dp[n-1][k];
}
};