print all possible products from a list of primes: product of two numbers, product of three number, etc.
第一题prime product(给你一组素数,求所有可能的乘积) , follow-up如果有重复怎么办,就跟LC上的subsets几乎一模一样。

Solution 1: DFS O(n * 2^n); O(n)
    public List<Integer> primeProduct(int[] nums) {
        List<Integer> res = new ArrayList<>();
        if (nums == null) {
            return res;
        }

        dfs(res, 1, nums, 0);
        return res;
    }

    private void dfs(List<Integer> res, int product, int[] nums, int start) {
        if (product != 1) {
            res.add(product);
        }

        for (int i = start; i < nums.length; i++) {
            product *= nums[i];
            dfs(res, product, nums, i + 1); //i + 1 avoid using a number multiple times
            product /= nums[i];
        }
    }

    public static void main(String[] args) {
        PrimeProduct test = new PrimeProduct();
        int[] nums = {2, 3, 5, 7}; // 1 is not a prime.
        int[] nums1 = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};
        System.out.println(test.primeProduct(nums));
        System.out.println(test.primeProduct(nums1));
    }
Follow Up:

1.如果有重复怎么办

    /**
     * DFS O(n * 2^n); O(n)
     */
    public List<Integer> primeProduct(int[] nums) {
        List<Integer> res = new ArrayList<>();
        if (nums == null) {
            return res;
        }

        Arrays.sort(nums);
        dfs(res, 1, nums, 0);
        return res;
    }

    private void dfs(List<Integer> res, int product, int[] nums, int start) {
        if (product != 1) {
            res.add(product);
        }

        for (int i = start; i < nums.length; i++) {
            if (i != start && nums[i] == nums[i - 1]) { //去重
                continue;
            }
            product *= nums[i];
            dfs(res, product, nums, i + 1);
            product /= nums[i];
        }
    }

results matching ""

    No results matching ""