day24

1、leetcode77 组合

class Solution {
    List<Integer> path = new LinkedList<Integer>();// 用来存放符合条件结果
    List<List<Integer>> res = new ArrayList<>();// 存放符合条件结果的集合

    public void backTracking(int n, int k, int startIndex) {
        if(path.size() == k) {
            res.add(new ArrayList<>(path));
            return;
        }

        for(int i=startIndex; i <= n - (k - path.size()) + 1; i++){//优化
            path.add(i);// 处理节点 
            backTracking(n, k, i+1);// 递归
            path.remove(path.size()-1);// 回溯,撤销处理的节点
        }
    }

    public List<List<Integer>> combine(int n, int k) {
        backTracking(n, k, 1);
        return res;
    }
}
posted @ 2023-02-13 23:55  黄三七  阅读(13)  评论(0)    收藏  举报