@@ -54,4 +54,110 @@ edit_url: https://github.com/doocs/leetcode/edit/main/lcp/LCP%2080.%20%E7%94%9F%
54
54
55
55
<!-- solution:start -->
56
56
57
+ ### 方法一:DFS
58
+
59
+ <!-- tabs:start -->
60
+
61
+ #### Python3
62
+
63
+ ``` python
64
+ class Solution :
65
+ def evolutionaryRecord (self , parents : List[int ]) -> str :
66
+ def dfs (i : int ) -> str :
67
+ t = sorted (dfs(j) for j in g[i])
68
+ return " 0" + " " .join(t) + " 1"
69
+
70
+ n = len (parents)
71
+ g = [[] for _ in range (n)]
72
+ for i in range (1 , n):
73
+ g[parents[i]].append(i)
74
+ return dfs(0 )[1 :].rstrip(" 1" )
75
+ ```
76
+
77
+ #### Java
78
+
79
+ ``` java
80
+ class Solution {
81
+ private List<Integer > [] g;
82
+
83
+ public String evolutionaryRecord (int [] parents ) {
84
+ int n = parents. length;
85
+ g = new List [n];
86
+ Arrays . setAll(g, k - > new ArrayList<> ());
87
+ for (int i = 1 ; i < n; ++ i) {
88
+ g[parents[i]]. add(i);
89
+ }
90
+ return dfs(0 ). substring(1 ). replaceAll(" 1+$" , " " );
91
+ }
92
+
93
+ private String dfs (int i ) {
94
+ List<String > t = new ArrayList<> ();
95
+ for (int j : g[i]) {
96
+ t. add(dfs(j));
97
+ }
98
+ Collections . sort(t);
99
+ return " 0" + String . join(" " , t) + " 1" ;
100
+ }
101
+ }
102
+ ```
103
+
104
+ #### C++
105
+
106
+ ``` cpp
107
+ class Solution {
108
+ public:
109
+ string evolutionaryRecord(vector<int >& parents) {
110
+ int n = parents.size();
111
+ vector<vector<int >> g(n);
112
+ for (int i = 1; i < n; ++i) {
113
+ g[ parents[ i]] .push_back(i);
114
+ }
115
+
116
+ function<string(int)> dfs = [&](int i) -> string {
117
+ vector<string> t;
118
+ for (int j : g[i]) {
119
+ t.push_back(dfs(j));
120
+ }
121
+ sort (t.begin(), t.end());
122
+ string res = "0";
123
+ for (const string& s : t) {
124
+ res += s;
125
+ }
126
+ res += "1";
127
+ return res;
128
+ };
129
+
130
+ string ans = dfs(0);
131
+ return ans.substr(1, ans.find_last_not_of('1'));
132
+ }
133
+ };
134
+ ```
135
+
136
+ #### Go
137
+
138
+ ```go
139
+ func evolutionaryRecord(parents []int) string {
140
+ n := len(parents)
141
+ g := make([][]int, n)
142
+ for i := 1; i < n; i++ {
143
+ g[parents[i]] = append(g[parents[i]], i)
144
+ }
145
+
146
+ var dfs func(int) string
147
+ dfs = func(i int) string {
148
+ var t []string
149
+ for _, j := range g[i] {
150
+ t = append(t, dfs(j))
151
+ }
152
+ sort.Strings(t)
153
+ return "0" + strings.Join(t, "") + "1"
154
+ }
155
+
156
+ ans := dfs(0)[1:]
157
+ return strings.TrimRight(ans, "1")
158
+ }
159
+ ```
160
+
161
+ <!-- tabs:end -->
162
+
57
163
<!-- problem:end -->
0 commit comments