DFS-找出数组中所有组合为target

题目:
给出[2,2, 3,4,7],找出所有组合target = 7
example: [2,2,4]、[3,4]、[7]

/**
 * Author:m
 * Date: 2023/04/08 8:26
 */
public class Target7 {
    
    
    private static final int TARGET = 7;
    public static void main(String[] args) {
    
    
        int[] array = new int[]{
    
    2, 2, 3, 4, 7};
        List<List<Integer>> result = dfs(array);
        System.out.println(result);
    }

    private static List<List<Integer>> dfs(int[] array) {
    
    
        if (array == null) {
    
    
            return Lists.newArrayList();
        }

        List<List<Integer>> result = Lists.newArrayList();
        List<Integer> combine = Lists.newArrayList();
        int initIndex = 0;
        int sum = 0;
        recursion(result, combine, array, initIndex, sum);
        return result;
    }

    private static void recursion(List<List<Integer>> result, List<Integer> combine, int[] array, int initIndex, Integer sum) {
    
    

        // 1.终止条件
        if (sum > TARGET) {
    
    
            return;
        }

        // 2.小集合添加至大集合
        if (sum == TARGET) {
    
    
            result.add(Lists.newArrayList(combine));
            return;//sum已经等于target了,以combine为基础的元素再去结合别的元素求和,只会越来越大于target,无需继续了
        }

        // 3.for循环
        for (int i = initIndex; i < array.length; i++) {
    
    
            // 3.1添加元素到小集合
            combine.add(array[i]);
            // 3.2递归(i+1)
            recursion(result, combine, array, i +1, sum + array[i]);
            // 3.3回溯(小集合删除最后一个元素)
            combine.remove(combine.size() - 1);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/tmax52HZ/article/details/130046720