算法修炼Day24| 77. 组合

60 阅读1分钟
题目:77. 组合 - 力扣(LeetCode)
思路/想法:

回溯算法,for循环进行横向遍历。递归进行深度遍历。 递归三部曲:确定递归函数及其参数,确定终止条件,确定单层搜索的逻辑。

代码实现:
class Solution {
    List<List<Integer>> ans = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();
    public List<List<Integer>> combine(int n, int k) {
        backtracking(n, k, 1);
        return ans;
    }
    public void backtracking(int n, int k, int startIndex) {
        if (path.size() == k) {
            ans.add(new ArrayList<>(path));
            return;
        }
        for (int i = startIndex; i <= n; i++) {
            path.add(i);
            backtracking(n, k, i + 1);
            path.removeLast();
        }
    }
}