給定一組不含重複元素的整數數組 nums,返回該數組所有可能的子集(冪集)。
說明:解集不能包含重複的子集。
示例:
輸入: nums = [1,2,3]
輸出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
分析:由於題目要求要列出所有的結果,所以我們很容易想到深搜法來遍歷所有的情況,但當面對數據量大的題目,深搜算法並沒有那麼好用,本題也可從另一個角度看待這個問題,對[1,2,3]來說,首先是[],然後遇到1,這時可以把[1]看成1和[]的合成形成[1],然後再遇到2,形成的序列有[2]、[1,2]。依次類推,可以形成的序列還有,[3]、[2,3]、[1,2,3]。這樣就算出所有的序列了。
深搜:
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res=new ArrayList<>();
dfs(res,new ArrayList<Integer>(),nums,0);
return res;
}
public static void dfs(List<List<Integer>> res,List<Integer> tmp,int[] nums,int start){
res.add(new ArrayList<Integer>(tmp));
for(int i=start;i<nums.length;i++){
tmp.add(nums[i]);
dfs(res,tmp,nums,i+1);
tmp.remove(tmp.size()-1);
}
}
}
直接計算:
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res=new ArrayList<>();
List<Integer> tmp=new ArrayList<>();
res.add(tmp);
int l=0;
for(int i=0;i<nums.length;i++){
l=res.size();
for(int j=0;j<l;j++){
tmp=new ArrayList<>(res.get(j));
tmp.add(nums[i]);
res.add(tmp);
}
}
return res;
}
}