leetcode78. Subsets

題目要求

Given a set of distinct integers, nums, return all possible subsets.

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],
  []
]

相似的題目有:
leetcode60 Permutation Sequence 能夠參考這篇博客
leetcode77 Combinations 能夠參考這篇博客面試

思路一:遞歸

仍是利用遞歸的方式,在前一種狀況的基礎上遍歷下一輪的組合狀況。segmentfault

public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        result.add(new ArrayList<Integer>());
        subsets(result, nums, 0, new ArrayList<Integer>());
        return result;
    }
    
    public void subsets(List<List<Integer>> result, int[] nums, int startIndex, List<Integer> currentList){
        if(startIndex == nums.length){
            return;
        }
        while(startIndex<nums.length){
            currentList.add(nums[startIndex++]);
            result.add(new ArrayList<Integer>(currentList));
            subsets(result, nums, startIndex, currentList);
            currentList.remove(currentList.size()-1);
        }
    }

思路2:排序後循環

起始subset集爲:[]
添加S0後爲:[], [S0]
添加S1後爲:[], [S0], [S1], [S0, S1]
添加S2後爲:[], [S0], [S1], [S0, S1], [S2], [S0, S2], [S1, S2], [S0, S1, S2]微信

public List<List<Integer>> subsets(int[] S) {
    List<List<Integer>> res = new ArrayList<>();
    res.add(new ArrayList<Integer>());
    
    for(int i : S) {
        List<List<Integer>> tmp = new ArrayList<>();
        for(List<Integer> sub : res) {
            List<Integer> a = new ArrayList<>(sub);
            a.add(i);
            tmp.add(a);
        }
        res.addAll(tmp);
    }
    return res;
}

clipboard.png
想要了解更多開發技術,面試教程以及互聯網公司內推,歡迎關注個人微信公衆號!將會不按期的發放福利哦~spa

相關文章
相關標籤/搜索