DAY 18
0

## 【從面試題學邏輯-18】用遞迴找子集似乎把事情搞得更難懂了……（leetcode 78. Subsets）

【從面試題學邏輯-16】拔智齒可以不要寫鐵人賽嗎？好像不能這樣做诶（leetcode 78. Subsets）

1. 設定一個終止條件，把空List丟回去
2. 把上一步拿到的subsets，分別加入這一步要加的元素
3. 把新產生的newSubsets塞進去subsets

``````class Solution {
public List<List<Integer>> subsets(int[] nums) {
return getSubsets(nums, 0);
}

public List<List<Integer>> getSubsets(int[] set, int index){
List<List<Integer>> subsets;
if (set.length == index) {
subsets = new ArrayList<List<Integer>>();
} else {
subsets = getSubsets(set, index+1);
int element = set[index];
List<List<Integer>> newSubsets = new ArrayList<List<Integer>>();
for(List<Integer> s : subsets) {
List<Integer> newSubset = new ArrayList<Integer>();
for(Integer n: s) {
}
}
for(List<Integer> s : newSubsets) {
}
}
return subsets;
}
}
``````

``````public List<List<Integer>> subsets(int[] nums) {
return getSubsets(nums, 0);
}
``````

``````public List<List<Integer>> getSubsets(int[] set, int index{
// 暫時省略中間
}
``````

``````if (set.length == index) {
subsets = new ArrayList<List<Integer>>();
}
``````

``````subsets = getSubsets(set, index+1);
``````

``````int element = set[index];
List<List<Integer>> newSubsets = new ArrayList<List<Integer>>();
``````

``````for(List<Integer> s : subsets) {
List<Integer> newSubset = new ArrayList<Integer>();
for(Integer n: s) {
}
}
``````

``````for(List<Integer> s : newSubsets) {
}
``````