Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

组合 #32

Open
louzhedong opened this issue Jun 13, 2018 · 0 comments
Open

组合 #32

louzhedong opened this issue Jun 13, 2018 · 0 comments

Comments

@louzhedong
Copy link
Owner

习题

出处:LeetCode 算法第77题

给定两个整数 nk,返回 1 ... n 中所有可能的 k 个数的组合。

示例:

输入: n = 4, k = 2
输出:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

思路

还是采取深度优先遍历,当组合的个数达到要求时存入结果中

解答

var combine = function (n, k) {
  var result = [];
  var temp = [];

  DFS(result, temp, 1, n + 1, k);
  return result;
};

function copy(array) {
  var result = [];
  for (var i = 0, len = array.length; i < len; i++) {
    result.push(array[i]);
  }
  return result;
}

function DFS(result, temp, index, n, k) {
  if (temp.length == k) {
    result.push(copy(temp));
    return;
  }
  if (index < n) {
    for (var p = index; p < n; p++) {
      temp.push(p);
      DFS(result, temp, p + 1, n, k);
      temp.pop();
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant