组合总和(Java)

it2025-05-30  11

给定一个无重复元素的数组 arr 和一个目标数 target ,找出 arr 中所有可以使数字和为 target 的组合。 arr 中的数字可以无限制重复被选取。

说明:     所有数字(包括 target)都是正整数。     解集不能包含重复的组合。

示例 1: 输入:arr = [2,3,6,7], target = 7, 所求解集为:组合总和 [   [7],   [2,2,3] ]

示例 2: 输入:arr = [2,3,5], target = 8, 所求解集为: [   [2,2,2,2],   [2,3,3],   [3,5] ]

package com.loo;

import java.util.List; import java.util.ArrayList;

public class CombinationSum {     public static void main(String[] args) {         int[] arr = new int[] { 2 ,3 , 6 , 7 };         int target = 7;         List<List<Integer>> list = combinationSum(arr , target);         for (List<Integer> l : list) {             System.out.println(l);         }         int[] arr2 = new int[] { 2 ,3 , 5 };         target = 8;         List<List<Integer>> list2 = combinationSum(arr2 , target);         for (List<Integer> l : list2) {             System.out.println(l);         }     }

    public static List<List<Integer>> combinationSum(int[] arr , int target) {         List<List<Integer>> list = new ArrayList<List<Integer>>();         List<Integer> com = new ArrayList<Integer>();         if (arr == null || arr.length == 0) {             return list;         }         dfsCombinationSum(arr , target , list , com , 0);         return list;     }

    public static void dfsCombinationSum(int[] arr , int target , List<List<Integer>> list , List<Integer> com , int index) {         if (index == arr.length) {             return;         }         if (target == 0) {             list.add(new ArrayList<Integer>(com));             return;         }         dfsCombinationSum(arr , target , list , com , index + 1);         if (target - arr[index] >= 0) {             com.add(arr[index]);             dfsCombinationSum(arr , target - arr[index] , list , com , index);             com.remove(com.size()-1);         }     } }

 

最新回复(0)