Skip to content

Commit b1ad080

Browse files
tianzhongweilabuladong
authored andcommitted
Update 子集排列组合.md
添加对应的C++版本
1 parent 38bc024 commit b1ad080

File tree

1 file changed

+40
-2
lines changed

1 file changed

+40
-2
lines changed

高频面试系列/子集排列组合.md

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,7 @@ vector<vector<int>> permute(vector<int>& nums);
199199
![](../pictures/子集/3.jpg)
200200

201201
我们当时使用 Java 代码写的解法:
202-
202+
[labuladong](https://github.com/labuladong) 提供Java解法代码:
203203
```java
204204
List<List<Integer>> res = new LinkedList<>();
205205

@@ -231,6 +231,44 @@ void backtrack(int[] nums, LinkedList<Integer> track) {
231231
}
232232
}
233233
```
234+
[renxiaoyao](https://github.com/tianzhongwei) 提供C++解法代码:
235+
```C++
236+
class Solution {
237+
public:
238+
vector<vector<int>> permute(vector<int>& nums) {
239+
paths.clear();
240+
path.clear();
241+
242+
vector<int> used(nums.size(),false);
243+
244+
helper(nums,used);
245+
246+
return paths;
247+
}
248+
private:
249+
void helper(vector<int>& nums,vector<int>& used) {
250+
if(path.size() == nums.size()) {
251+
paths.push_back(path);
252+
return ;
253+
}
254+
255+
for(int i = 0 ; i < nums.size() ; ++i) {
256+
if(used[i]) continue;
257+
258+
used[i] = true;
259+
path.push_back(nums[i]);
260+
261+
helper(nums,used);
262+
263+
path.pop_back();
264+
used[i] = false;
265+
}
266+
}
267+
private:
268+
vector<vector<int>> paths;
269+
vector<int> path;
270+
};
271+
```
234272
235273
回溯模板依然没有变,但是根据排列问题和组合问题画出的树来看,排列问题的树比较对称,而组合问题的树越靠右节点越少。
236274
@@ -255,4 +293,4 @@ void backtrack(int[] nums, LinkedList<Integer> track) {
255293
256294
[下一篇:二分查找详解](../算法思维系列/二分查找详解.md)
257295
258-
[目录](../README.md#目录)
296+
[目录](../README.md#目录)

0 commit comments

Comments
 (0)