DFS-找出数组中所有组合为target值的(结果不重复)

1、题目:
找出[2,2,3,3,4,7]中所有组合target=7
2、注意:组合不能重复
即[2,2,3] 和 [2,2,3]虽然都满足target=7,但是属于重复组合
同理[3,4]和 [3,4]也重复了
3、元素不允许被多次使用
4、满足的组合有:
[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);
        }
    }
}

猜你喜欢

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