1. 程式人生 > >78.Subsets leetcode java

78.Subsets leetcode java

題目:

Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,3], a solution is:

[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]
給定一個不重複整數的集合,返回所有可能的子集,解集不能包含重複的子集

思路:

看到all possible subsets是典型的DFS,套用排列組合模板

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        List<Integer> subset = new ArrayList<Integer>();
        if(nums.length==0){
            return res;
        }
        Arrays.sort(nums);
        helper(subset,nums,0,res);
        return res;
    }
    public void helper(List<Integer> subset,int[] nums,int pos,List<List<Integer>> res){//找到所有以subset開頭的所有子集
        res.add(new ArrayList<Integer>(subset));//因為java傳的是引用,如果直接把subsetadd進去,之後subset變化後add進去的物件也會發生變化,這裡相當於拍個快照add進去
        for(int i=pos;i<nums.length;i++){
            subset.add(nums[i]);
            helper(subset,nums,i+1,res);
            subset.remove(subset.size()-1);
        }
    }
}