硬币凑整问题

引言

硬币凑整问题
题目来源:力扣 https://leetcode-cn.com/circle/discuss/vMYOmI/

题目描述

已知一个无序数组 array,元素均为正整数。给定一个目标值 target,输出数组中是否存在若干元素的组合,相加为目标值。

测试样例与说明

对于以下无序数组

3, 9, 5, 8, 7, 17

输出

[3, 5, 8]
[9, 7]

解题

    /**
     * 
     * @param arr 给定数组
     * @param index  数组当前索引
     * @param sum  累计和
     * @param target 给定的目标值
     */
    public static void m(int[] arr, int index, int sum, int target) {
        if (index == arr.length) {
            return;
        }
        //入栈
        list.addLast(arr[index]);
        if (target == sum + arr[index]) {
            System.out.println(list);
            list.removeLast();
            return;
        }
        if (arr[index] + sum < target) {
            m(arr, index + 1, sum + arr[index], target);
        }
        list.removeLast();
        m(arr, index + 1, sum, target);
    }

    //使用链表充当栈
    static LinkedList<Integer> list = new LinkedList();

    //测试用例
    public static void main(String[] args) {
        int[] nums = {3, 9, 5, 8, 7, 17};
        int target = 16;
        m(nums, 0, 0, target);

    }
posted @ 2021-05-13 17:11  心若向阳花自开  阅读(256)  评论(0编辑  收藏  举报