36
36
<li><code>nums</code> 中的所有元素 <strong>互不相同</strong></li>
37
37
</ul >
38
38
39
-
40
39
## 解法
41
40
42
41
<!-- 这里可写通用的实现逻辑 -->
@@ -67,15 +66,18 @@ def backtrack(未探索区域, res, path):
67
66
``` python
68
67
class Solution :
69
68
def subsets (self , nums : List[int ]) -> List[List[int ]]:
70
- def dfs (nums , i , res , path ):
71
- res.append(copy.deepcopy(path))
72
- while i < len (nums):
73
- path.append(nums[i])
74
- dfs(nums, i + 1 , res, path)
75
- path.pop()
76
- i += 1
77
- res, path = [], []
78
- dfs(nums, 0 , res, path)
69
+ res = []
70
+
71
+ def dfs (i , n , t ):
72
+ res.append(t.copy())
73
+ if i == n:
74
+ return
75
+ for j in range (i, n):
76
+ t.append(nums[j])
77
+ dfs(j + 1 , n, t)
78
+ t.pop()
79
+
80
+ dfs(0 , len (nums), [])
79
81
return res
80
82
```
81
83
@@ -86,24 +88,75 @@ class Solution:
86
88
``` java
87
89
class Solution {
88
90
public List<List<Integer > > subsets (int [] nums ) {
89
- List<Integer > path = new ArrayList<> ();
90
91
List<List<Integer > > res = new ArrayList<> ();
91
- dfs(nums, 0 , res, path );
92
+ dfs(0 , nums, new ArrayList<> (), res );
92
93
return res;
93
94
}
94
95
95
- private void dfs (int [] nums , int i , List<List<Integer > > res , List<Integer > path ) {
96
- res. add(new ArrayList<> (path));
97
- while (i < nums. length) {
98
- path. add(nums[i]);
99
- dfs(nums, i + 1 , res, path);
100
- path. remove(path. size() - 1 );
101
- ++ i;
96
+ private void dfs (int i , int [] nums , List<Integer > t , List<List<Integer > > res ) {
97
+ res. add(new ArrayList<> (t));
98
+ if (i == nums. length) {
99
+ return ;
100
+ }
101
+ for (int j = i; j < nums. length; ++ j) {
102
+ t. add(nums[j]);
103
+ dfs(j + 1 , nums, t, res);
104
+ t. remove(t. size() - 1 );
102
105
}
103
106
}
104
107
}
105
108
```
106
109
110
+ ### ** C++**
111
+
112
+ ``` cpp
113
+ class Solution {
114
+ public:
115
+ vector<vector<int >> subsets(vector<int >& nums) {
116
+ vector<vector<int >> res;
117
+ vector<int > t;
118
+ dfs(0, nums, t, res);
119
+ return res;
120
+ }
121
+
122
+ void dfs(int i, vector<int>& nums, vector<int> t, vector<vector<int>>& res) {
123
+ res.push_back(t);
124
+ if (i == nums.size()) return;
125
+ for (int j = i; j < nums.size(); ++j)
126
+ {
127
+ t.push_back(nums[j]);
128
+ dfs(j + 1, nums, t, res);
129
+ t.pop_back();
130
+ }
131
+ }
132
+ };
133
+ ```
134
+
135
+ ### ** Go**
136
+
137
+ ``` go
138
+ func subsets (nums []int ) [][]int {
139
+ var res [][]int
140
+ var t []int
141
+ dfs (0 , nums, t, &res)
142
+ return res
143
+ }
144
+
145
+ func dfs (i int , nums , t []int , res *[][]int ) {
146
+ cp := make ([]int , len (t))
147
+ copy (cp, t)
148
+ *res = append (*res, cp)
149
+ if i == len (nums) {
150
+ return
151
+ }
152
+ for j := i; j < len (nums); j++ {
153
+ t = append (t, nums[j])
154
+ dfs (j+1 , nums, t, res)
155
+ t = t[:len (t)-1 ]
156
+ }
157
+ }
158
+ ```
159
+
107
160
### ** ...**
108
161
109
162
```
0 commit comments