Subset problem_ output all subsets without repeating numbers

Input an array of unique numbers and output all subsets of all these numbers

Such as [1,2,3]

Output: [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]

dynamic programming

/**
 * description: 输入一个不重复序列,输出这些数字的所有子集
 */
public class ChildCollection {
    static LinkedList<LinkedList<Integer>> result = new LinkedList<>();

    public static void main(String[] args) {
        List<Integer> nums = Arrays.asList(1, 2, 3);
        LinkedList<Integer> tmp = new LinkedList<>();
        findChildCollection(nums, tmp, 0);
        System.out.println(result);
    }

    /**
     * 子集
     *
     * @param nums
     * @param tmp
     * @param num
     */
    public static void findChildCollection(List<Integer> nums, LinkedList<Integer> tmp, int num) {
        result.add(new LinkedList<>(tmp));
        for (int i = num; i < nums.size(); i++) {
            Integer integer = nums.get(i);
            if (tmp.contains(integer)) {
                continue;
            }
            tmp.add(integer);
            findChildCollection(nums, tmp, i);
            tmp.removeLast();
        }
    }
}

Guess you like

Origin blog.csdn.net/haohaounique/article/details/123608007