[刷题记录Day 24]Leetcode组合之回溯算法

No.1

题目

组合

思路

  • 回溯法

递归分析

  1. 全局变量:存放符合条件单一结果的集合path,存放符合条件结果的集合result
  2. 返回值:空,参数nkstartIndex(记录递归搜索的起始位置)
  3. 终止条件path.size() == k,就存储结果,返回
  4. 单层递归逻辑:从startIndex开始遍历,处理节点,递归,回溯

代码

List<List<Integer>> result = new ArrayList<>();  
LinkedList<Integer> path = new LinkedList<>();  
public void combineHelper(int n, int k, int start) {  
    if (path.size() == k) {  
        result.add(new ArrayList<>(path));  
        return;  
    }  
  
    // 横向遍历  
    for (int i = start; i <= n; i++) {  
        // 处理当前节点  
        path.add(i);  
        // 递归  
        combineHelper(n, k, i + 1);  
        path.removeLast();  
    }  
}  
  
public List<List<Integer>> combine(int n, int k) {  
    combineHelper(n, k, 1);  
    return result;  
}
posted @ 2023-09-11 12:54  喜欢毛绒绒的番茄子  阅读(8)  评论(0)    收藏  举报