面试算法81:允许重复选择元素的组合

题目

给定一个没有重复数字的正整数集合,请找出所有元素之和等于某个给定值的所有组合。同一个数字可以在组合中出现任意次。例如,输入整数集合[2,3,5],元素之和等于8的组合有3个,分别是[2,2,2,2]、[2,3,3]和[3,5]。

分析

能够用回溯法解决的问题都能够分成若干步来解决,每一步都面临若干选择。对于从集合中选取数字组成组合的问题而言,集合中有多少个数字,解决这个问题就需要多少步。每一步都从集合中取出一个下标为i的数字,此时面临两个选择。一个选择是跳过这个数字不将该数字添加到组合中,那么这一步实际上什么都不做,接下来处理下标为i+1的数字。另一个选择是将数字添加到组合中,由于一个数字可以重复在组合中出现,也就是说,下一步可能再次选择同一个数字,因此下一步仍然处理下标为i的数字。

java 复制代码
public class Test {
    public static void main(String[] args) {
        int[] nums = {2, 3, 5};
        List<List<Integer>> result = combinationSum(nums, 8);
        for (List<Integer> item : result) {
            System.out.println(item);
        }
    }

    public static List<List<Integer>> combinationSum(int[] nums, int target) {
        List<List<Integer>> result = new LinkedList<>();
        LinkedList<Integer> combination = new LinkedList<>();
        helper(nums, target, 0, combination, result);

        return result;
    }

    private static void helper(int[] nums, int target, int i, LinkedList<Integer> combination,
        List<List<Integer>> result) {
        if (target == 0) {
            result.add(new LinkedList<>(combination));
        }
        else if (target > 0 && i < nums.length) {
            helper(nums, target, i + 1, combination, result);

            combination.add(nums[i]);
            helper(nums, target - nums[i], i, combination, result);
            combination.removeLast();
        }
    }
}
相关推荐
快去睡觉~1 小时前
力扣73:矩阵置零
算法·leetcode·矩阵
小欣加油2 小时前
leetcode 3 无重复字符的最长子串
c++·算法·leetcode
月盈缺4 小时前
学习嵌入式的第二十二天——数据结构——双向链表
数据结构·学习·链表
猿究院--王升4 小时前
jvm三色标记
java·jvm·算法
一车小面包5 小时前
逻辑回归 从0到1
算法·机器学习·逻辑回归
科大饭桶6 小时前
C++入门自学Day14-- Stack和Queue的自实现(适配器)
c语言·开发语言·数据结构·c++·容器
tt5555555555556 小时前
字符串与算法题详解:最长回文子串、IP 地址转换、字符串排序、蛇形矩阵与字符串加密
c++·算法·矩阵
元亓亓亓7 小时前
LeetCode热题100--101. 对称二叉树--简单
算法·leetcode·职场和发展
躲在云朵里`7 小时前
深入理解数据结构:从数组、链表到B树家族
数据结构·b树
不会学习?7 小时前
算法03 归并分治
算法