思路
先序遍历树,记录路径就可以
详细看代码
思路是跟y总学的
C++ 代码
#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
const int N = 110;
int w[N];
vector<int>tree[N];
int n, m, S;
vector<vector<int>>path;//从头结点到叶子结点存储路径和路径的
void dfs(int root, int sum, vector<int>s)
{
if (tree[root].size() != 0)//非叶子结点
{
for (int val : tree[root])
{
s.push_back(w[val]);
dfs(val, sum + w[val], s);
s.pop_back();
}
}
else
{
if (sum == S)
path.push_back(s);
return;
}
}
int main()
{
cin >> n >> m >> S;
for (int i = 0; i < n; i++)
cin >> w[i];
int id, num, temp;
while (m--)
{
cin >> id >> num;
for (int i = 0; i < num; i++)
{
cin >> temp;
tree[id].push_back(temp);
}
}
vector<int>ss;
ss.push_back(w[0]);
dfs(00, w[0], ss);
sort(path.begin(), path.end(), greater<vector<int>>());
for (auto i : path)
{
for (int j = 0; j < i.size(); j++)
{
cout << i[j];
if (j != i.size() - 1)
cout << ' ';
}
cout << endl;
}
return 0;
}
算法2
(暴力枚举) $O(n^2)$
blablabla
时间复杂度
参考文献
C++ 代码
blablabla