LeetCode 40 组合总和 II dfs

// 跟上题类似,只是需要去重方面考虑的多一些
// 开始暴力去重,发现效率很低...
// 后来参考大牛们的博客才发现,原来只要在每次递归的时候
// 就可以去重,比如:
// 1 1 2 2 3
// 1放入 ,第二个1在这轮循环中不需要再放入,注意是这轮循环
// 递归不到家....哎...继续加油!



class Solution {
    boolean[] flag = null;
    public List<List<Integer>> combinationSum2(int[] condidates, int target){
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> ans = new ArrayList<>();
        flag = new boolean[condidates.length];
        Arrays.fill(flag, false);
        Arrays.sort(condidates);
        dfs(res, ans, condidates, 0, target);
        return res;
    }

    public void dfs(List<List<Integer>> res, List<Integer> ans, int[] condidates, int index, int target){

        if (target == 0){
            // boolean tag = false;
            // for (List<Integer> list : res){
            //     int i = 0;
            //     for (i = 0;i < list.size(); i ++){
            //         if (list.get(i) != ans.get(i))
            //             break;
            //     }

            //     if (i == list.size()){
            //         tag = true;
            //     }
            // }
            // if (!tag)
            res.add(ans);
            return ;
        }

        for (int i = index;i < condidates.length; i ++)
            if (!flag[i] && condidates[i] <= target){  
                if (i != index && condidates[i] == condidates[i - 1]) continue; // 这轮循环相同的不必再放入

                List<Integer> tmp = new ArrayList<>(ans);
                tmp.add(condidates[i]);
                flag[i] = true;
                dfs(res, tmp, condidates, i + 1, target - condidates[i]);
                flag[i] = false;
            }
    }
}

猜你喜欢

转载自blog.csdn.net/TIMELIMITE/article/details/89891719