アルゴリズム:指定は組み合わせの数は、8つの組み合わせをバックアップ

タイトル

住所:https://leetcode.com/problems/combinations/

二つの整数nとkが与えられ、nは1 ...のうちk個のすべての可能な組み合わせを返します。

例:

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 ビュー20000 +

おすすめ

転載: blog.csdn.net/zgpeace/article/details/103829535