LeetCode排列組合問題合集

78. Subsets

Given a set of distinct integers, nums, return all possible subsets.
給定一組非重複數字,求出所有可能的子集

解析:

例如 [1,2,3],解法:
首先放[],然後往已有的[]中放1
1. 首先放1
此時已有[ [], 1 ]
2. 然後對[ [], 1 ] 放2
於是此時有 [ [], [1], [2], [1,2] ]
3. 然後對[ [], [1], [2], [1,2] ] 放3
此時[ [], [1], [2], [1,2], [3], [1,3], [2,3], [1,2,3] ] 求出解

算法

public class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        result.add(new ArrayList<Integer>());

        Arrays.sort(nums);
        //算法思想:往當前已有的組合中添加
        for (int i : nums) {
            List<List<Integer>> tmp = new ArrayList<>();
            for (List<Integer> a : result) {
                List<Integer> sub = new ArrayList<>(a);
                sub.add(i);
                tmp.add(sub);
            }
            result.addAll(tmp);
        }
        return result;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章