面试算法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();
        }
    }
}
相关推荐
Python×CATIA工业智造19 分钟前
详细页智能解析算法:洞悉海量页面数据的核心技术
爬虫·算法·pycharm
无聊的小坏坏1 小时前
力扣 239 题:滑动窗口最大值的两种高效解法
c++·算法·leetcode
黎明smaly1 小时前
【排序】插入排序
c语言·开发语言·数据结构·c++·算法·排序算法
YuTaoShao1 小时前
【LeetCode 热题 100】206. 反转链表——(解法一)值翻转
算法·leetcode·链表
YuTaoShao2 小时前
【LeetCode 热题 100】142. 环形链表 II——快慢指针
java·算法·leetcode·链表
CCF_NOI.2 小时前
(普及−)B3629 吃冰棍——二分/模拟
数据结构·c++·算法
掘金安东尼2 小时前
革新Web部署:Amazon Amplify Hosting!
后端·面试·github
掘金安东尼2 小时前
把复杂留给架构,把简单留给开发 —— Amazon Aurora DSQL 宣布:全面可用
面试·架构·github
漫天星梦2 小时前
前端列表页大数据内存优化的思考
前端·面试
爱学习的茄子2 小时前
从0到1:揭秘前端网络请求的进化之路
前端·javascript·面试