力扣216 组合综合3

题目:

找出所有相加之和为 n 的 k 个数的组合,且满足下列条件:
    只使用数字1到9
    每个数字最多使用一次 
返回所有可能的有效组合的列表。该列表不能包含相同的组合两次,组合可以以任何顺序返回。

示例:

输入: k = 3, n = 9
输出: [[1,2,6], [1,3,5], [2,3,4]]
解释:
1 + 2 + 6 = 9
1 + 3 + 5 = 9
2 + 3 + 4 = 9
没有其他符合的组合了。

思路:

  自己画个图就清楚了(这里放个代码随想录的图)。

class Solution {
    List<List<Integer>> res=new ArrayList<>();
    LinkedList<Integer> path=new LinkedList<>();
    public List<List<Integer>> combinationSum3(int k, int n) {
        combinationSum3back(k,n,1);
        return res;
    }

    public void combinationSum3back(int k,int n,int startIndex){
        //终止条件
        if(path.size()==k){//当遍历到深度为k时
            int sum=0;
            for(int a:path){
                sum+=a;
            }
            if(sum==n){//并且当前路径节点和为n
                res.add(new ArrayList<>(path));//找到结果   
                return;  
            }
        }
        //回溯遍历过程
        for(int i=startIndex;i<=9;i++){
            path.add(i);//处理节点
            combinationSum3back(k,n,i+1);//递归
            path.removeLast();//回溯
        }
    }
}

剪枝处理:

class Solution {
    List<List<Integer>> res=new ArrayList<>();
    LinkedList<Integer> path=new LinkedList<>();
    public List<List<Integer>> combinationSum3(int k, int n) {
        combinationSum3back(k,n,1);
        return res;
    }

    public void combinationSum3back(int k,int n,int startIndex){
        //剪枝
        int sum=0;
        for(int a:path){
            sum+=a;
        }
        if(sum>n){
            return;
        }
        //终止条件
        if(path.size()==k&&sum==n){//当遍历到深度为k时//并且当前路径节点和为n
            res.add(new ArrayList<>(path));//找到结果   
            return;  
        }
        //回溯遍历过程
        /*for(int i=startIndex;i<=9;i++){
            path.add(i);//处理节点
            combinationSum3back(k,n,i+1);//递归
            path.removeLast();//回溯
        }*/
        for(int i=startIndex;i<=9-(k-path.size())+1;i++){
            path.add(i);//处理节点
            combinationSum3back(k,n,i+1);//递归
            path.removeLast();//回溯
        }
    }
}

 

posted @ 2023-02-28 21:18  壹索007  阅读(11)  评论(0编辑  收藏  举报