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

组合总和 #13

Open
louzhedong opened this issue Apr 28, 2018 · 0 comments
Open

组合总和 #13

louzhedong opened this issue Apr 28, 2018 · 0 comments

Comments

@louzhedong
Copy link
Owner

题目

出处:LeetCode 算法第39题

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的数字可以无限制重复被选取。

说明:

  • 所有数字(包括 target)都是正整数。
  • 解集不能包含重复的组合。

示例 1:

输入: candidates = [2,3,6,7], target = 7,
所求解集为:
[
  [7],
  [2,2,3]
]

示例 2:

输入: candidates = [2,3,5], target = 8,
所求解集为:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

思路

整体思路还是采用递归遍历的方法,遍历所有可能的组合。由于在JS 中数组是引用类型,所有要实现一个copy函数来实现数组的复制。

解答

var combinationSum = function (candidates, target) {
  var result = [];
  var temp = [];
  var sum = 0;
  candidates.sort(function (a, b) {
    return a - b;
  })
  DFS(candidates, sum, 0, target, temp, result);
  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(candidates, sum, level, target, temp, result) {
  if (sum > target) {
    return;
  }
  if (sum == target) {
    result.push(copy(temp));
    return;
  }
  for (var i = level; i < candidates.length; i  ) {
    sum  = candidates[i];
    temp.push(candidates[i]);
    DFS(candidates, sum, i, target, temp, result);
    temp.pop();
    sum -= candidates[i];
  }
}
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