@@ -42,13 +42,57 @@ Backtracking
42
42
### ** Python3**
43
43
44
44
``` python
45
-
45
+ class Solution :
46
+ def permutation (self , S : str ) -> List[str ]:
47
+ def dfs (u , t ):
48
+ if u == n:
49
+ ans.append(' ' .join(t))
50
+ return
51
+ for i in range (n):
52
+ if vis[i]:
53
+ continue
54
+ vis[i] = True
55
+ t.append(S[i])
56
+ dfs(u + 1 , t)
57
+ t.pop()
58
+ vis[i] = False
59
+
60
+ n = len (S)
61
+ vis = [False ] * n
62
+ ans = []
63
+ dfs(0 , [])
64
+ return ans
46
65
```
47
66
48
67
### ** Java**
49
68
50
69
``` java
70
+ class Solution {
71
+ public String [] permutation (String S ) {
72
+ Set<Character > vis = new HashSet<> ();
73
+ List<String > ans = new ArrayList<> ();
74
+ StringBuilder t = new StringBuilder ();
75
+ dfs(0 , S , t, ans, vis);
76
+ return ans. toArray(new String [0 ]);
77
+ }
51
78
79
+ private void dfs (int u , String S , StringBuilder t , List<String > ans , Set<Character > vis ) {
80
+ if (u == S . length()) {
81
+ ans. add(t. toString());
82
+ return ;
83
+ }
84
+ for (char c : S . toCharArray()) {
85
+ if (vis. contains(c)) {
86
+ continue ;
87
+ }
88
+ vis. add(c);
89
+ t. append(c);
90
+ dfs(u + 1 , S , t, ans, vis);
91
+ t. deleteCharAt(t. length() - 1 );
92
+ vis. remove(c);
93
+ }
94
+ }
95
+ }
52
96
```
53
97
54
98
### ** JavaSript**
@@ -85,6 +129,67 @@ function dfs(arr, depth, prev, record, res) {
85
129
}
86
130
```
87
131
132
+ ### ** C++**
133
+
134
+ ``` cpp
135
+ class Solution {
136
+ public:
137
+ vector<string > permutation(string S) {
138
+ unordered_set<char > vis;
139
+ vector<string > ans;
140
+ string t = "";
141
+ dfs(0, S, t, ans, vis);
142
+ return ans;
143
+ }
144
+
145
+ void dfs(int u, string& S, string& t, vector<string>& ans, unordered_set<char>& vis) {
146
+ if (u == S.size())
147
+ {
148
+ ans.push_back(t);
149
+ return;
150
+ }
151
+ for (char & c : S)
152
+ {
153
+ if (vis.count(c)) continue;
154
+ vis.insert(c);
155
+ t.push_back(c);
156
+ dfs (u + 1, S, t, ans, vis);
157
+ vis.erase(c);
158
+ t.pop_back();
159
+ }
160
+ }
161
+ };
162
+ ```
163
+
164
+ ### ** Go**
165
+
166
+ ``` go
167
+ func permutation (S string ) []string {
168
+ vis := make (map [byte ]bool )
169
+ var ans []string
170
+ var t []byte
171
+ var dfs func (u int , t []byte )
172
+ dfs = func (u int , t []byte ) {
173
+ if u == len (S) {
174
+ ans = append (ans, string (t))
175
+ return
176
+ }
177
+ for i := range S {
178
+ if vis[S[i]] {
179
+ continue
180
+ }
181
+ vis[S[i]] = true
182
+ t = append (t, S[i])
183
+ dfs (u+1 , t)
184
+ vis[S[i]] = false
185
+ t = t[:len (t)-1 ]
186
+ }
187
+ }
188
+ dfs (0 , t)
189
+ return ans
190
+ }
191
+ ```
192
+
88
193
### ** ...**
89
194
90
195
```
0 commit comments