算法:回溯八 Combinations指定个数组合

题目

地址:https://leetcode.com/problems/combinations/

Given two integers n and k, return all possible combinations of k numbers out of 1 … n.

Example:

Input: n = 4, k = 2
Output:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

DFS深度优先回溯

思路解析:

  1. 遍历所有数据,要么选择,要么不选择list.remove(list.size() - 1)
  2. 回溯的起点数据为1, 每次递归调用数字个数参数k的变化为k -1
  3. k == 0的时候,把数据添加到结果列表中.
  4. 提升效率亮点,循环遍历数据只考虑有效数据i <= n - k + 1
public List<List<Integer>> combine(int n, int k) {
  List<List<Integer>> resultList = new ArrayList<List<Integer>>();
  if (n == 0 || k == 0) {
    return resultList;
  }

  // dfs
  dfs(n, k, resultList, new ArrayList<Integer>(), 1);

  return resultList;
}

public void dfs(int n, int k, List<List<Integer>> resultList, List<Integer> list, int start) {
  if (k == 0) {
    resultList.add(new ArrayList<Integer>(list));
    return;
  }

  for (int i = start; i <= n - k + 1; i++) {
    // [1, 2], [1, 3], [1, 4]
    // [2, 3], [2, 4]
    // [3, 4]
    list.add(i);
    dfs(n, k - 1, resultList, list, i + 1);
    list.remove(list.size() - 1);
  }
}

公式算法C(n,k)=C(n-1,k-1)+C(n-1,k)

// based on C(n,k)=C(n-1,k-1)+C(n-1,k)
  public List<List<Integer>> combineBaseOnFormular(int n, int k) {
    List<List<Integer>> resultList = new LinkedList<List<Integer>>();
    if (n < k || k == 0) {
      return resultList;
    }
    resultList = combineBaseOnFormular(n - 1, k - 1);
    // if at this point resultList is empty, it can only be that k - 1 == 0,
    // n - 1 < k - 1 is not possible since n >= k (if n < k, the function would have already returned at an early point)
    if (resultList.isEmpty()) {
      resultList.add(new LinkedList<Integer>());
    }
    for (List<Integer> list: resultList) {
      list.add(n);
    }

    resultList.addAll(combineBaseOnFormular(n - 1, k));

    return resultList;
  }

代码下载

https://github.com/zgpeace/awesome-java-leetcode/blob/master/code/LeetCode/src/backtracking/Combinations.java

发布了127 篇原创文章 · 获赞 12 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/zgpeace/article/details/103829535