Skip to content

Commit

Permalink
Update 子集排列组合.md
Browse files Browse the repository at this point in the history
添加对应的C++版本
  • Loading branch information
tianzhongwei authored and labuladong committed Jun 22, 2020
1 parent 38bc024 commit b1ad080
Showing 1 changed file with 40 additions and 2 deletions.
42 changes: 40 additions & 2 deletions 高频面试系列/子集排列组合.md
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ vector<vector<int>> permute(vector<int>& nums);
![](../pictures/子集/3.jpg)

我们当时使用 Java 代码写的解法:

[labuladong](https://github.com/labuladong) 提供Java解法代码:
```java
List<List<Integer>> res = new LinkedList<>();

Expand Down Expand Up @@ -231,6 +231,44 @@ void backtrack(int[] nums, LinkedList<Integer> track) {
}
}
```
[renxiaoyao](https://github.com/tianzhongwei) 提供C++解法代码:
```C++
class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
paths.clear();
path.clear();

vector<int> used(nums.size(),false);

helper(nums,used);

return paths;
}
private:
void helper(vector<int>& nums,vector<int>& used) {
if(path.size() == nums.size()) {
paths.push_back(path);
return ;
}

for(int i = 0 ; i < nums.size() ; ++i) {
if(used[i]) continue;

used[i] = true;
path.push_back(nums[i]);
helper(nums,used);

path.pop_back();
used[i] = false;
}
}
private:
vector<vector<int>> paths;
vector<int> path;
};
```
回溯模板依然没有变,但是根据排列问题和组合问题画出的树来看,排列问题的树比较对称,而组合问题的树越靠右节点越少。
Expand All @@ -255,4 +293,4 @@ void backtrack(int[] nums, LinkedList<Integer> track) {
[下一篇:二分查找详解](../算法思维系列/二分查找详解.md)
[目录](../README.md#目录)
[目录](../README.md#目录)

0 comments on commit b1ad080

Please sign in to comment.