DFS-Find all combinations of target values in the array (the results are not repeated)

1. Topic:
Find all combinations target=7 in [2,2,3,3,4,7]
2. Note: Combinations cannot be repeated
, that is, although [2,2,3] and [2,2,3] are both Satisfy target=7, but it is a repeated combination.
Similarly, [3,4] and [3,4] also repeat
3. Elements are not allowed to be used multiple times.
4. Satisfied combinations are:
[2,2,3], [ 3,4], [7]

/**
 * Author:m
 * Date: 2023/04/08 11:01
 */
public class Target7ResultNotRepeat {
    
    

    private static final int TARGET = 7;
    public static void main(String[] args) {
    
    
        int[] array = new int[]{
    
    2, 3, 3, 4, 7};
        Arrays.sort(array);
        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 startIndex, Integer sum) {
    
    

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

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

        // 3.for循环
        for (int i = startIndex; i < array.length; i++) {
    
    
            // 3.0剪枝优化
            // 如果当前sum = 4,array[i] = 5, 那么sum + 5 > 7了。array是正序排序过的,后面的值只会越来愈大,sum加上他们只会比7更大,不可能为7了
            if (sum + array[i] > TARGET) {
    
    
                break;
            }
            // 3.0 不符合条件的结果直接在此不添加到combine中,而不是找出全部组合形式后,再对相同结果去重
            if (i != startIndex && array[i] == array[i - 1]) {
    
    
                continue;
            }
            // 3.1添加元素到小集合
            combine.add(array[i]);
            // 3.2递归(由于每一个元素可以重复使用,下一轮搜索的起点依然是 i,而不是i+1)
            recursion(result, combine, array, i, sum + array[i]);
            // 3.3回溯(小集合删除最后一个元素)
            combine.remove(combine.size() - 1);
        }
    }
}

Guess you like

Origin blog.csdn.net/tmax52HZ/article/details/130046837
Recommended