Leetcode - Subset

[分析] 三种思路
思路1:每层递归新加一个元素,第一层递归,在结果中加入空集,然后循环添加不同的第一个元素并向下递归;第二层递归,先将输入参数中包含一个元素的子集加入结果,然后循环添加不同的第二个元素并向下递归……第 n + 1层将包含 n个元素的全集加入结果。
思路2和思路3参考Code Ganker博客,分别是递归和迭代的思路,个人觉得迭代更好理解。
[ref]
subset: http://blog.csdn.net/linhuanmars/article/details/24286377

public class Solution {
    // Method 1
    public List<List<Integer>> subsets1(int[] nums) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        if (nums == null || nums.length == 0) {
            result.add(new ArrayList<Integer>());
            return result;
        }
        Arrays.sort(nums);
        recur(nums, 0, new ArrayList<Integer>(nums.length), result);
        return result;
    }
    public void recur(int[] nums, int start, List<Integer> subset, List<List<Integer>> result) {
        result.add(new ArrayList<Integer>(subset));
        for (int i = start; i < nums.length; i++) {
            subset.add(nums[i]);
            recur(nums, i + 1, subset, result);
            subset.remove(subset.size() - 1);
        }
    }
    // Method 2
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        if (nums == null || nums.length == 0) {
            result.add(new ArrayList<Integer>());
            return result;
        }
        Arrays.sort(nums);
        return recur(nums, nums.length - 1);
    }
    public List<List<Integer>> recur(int[] nums, int idx) {
        if (idx < 0) {
            List<List<Integer>> result = new ArrayList<List<Integer>>();
            result.add(new ArrayList<Integer>());
            return result;
        }
        List<List<Integer>> result = recur(nums, idx - 1);
        int size = result.size();
        for (int i = 0; i < size; i++) {
            List<Integer> newSubset = new ArrayList<Integer>(result.get(i));
            newSubset.add(nums[idx]);
            result.add(newSubset);
        }
        return result;
    }
    
    // Method 3
    public List<List<Integer>> subsets3(int[] nums) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        result.add(new ArrayList<Integer>());
        if (nums == null || nums.length == 0) {
            return result;
        }
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            int size = result.size();
            for (int j = 0; j < size; j++) {
                List<Integer> newSubset = new ArrayList<Integer>(result.get(j));
                newSubset.add(nums[i]);
                result.add(newSubset);
            }
        }
        return result;
    }
}

你可能感兴趣的:(LeetCode)