2016年12月8日 星期四

[LeetCode] 39. Combination Sum

轉自LeetCode

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is: 
[
  [7],
  [2, 2, 3]
]
<Solution>

要求排列組合,並且有個最終滿足條件 => DFS

這題要注意一個地方是,數字可以重複用,這點處理好就可以了

code 如下
c++
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> ans;
vector<int> out;
//> use DFS
combineByDFS(0, target, candidates, out, ans);
return ans;
}
void combineByDFS(const int &start, const int &target, vector<int> &candidates, vector<int> &out, vector<vector<int>> &ans) {
if(target == 0) {
//> find answer
ans.push_back(out);
}
else {
for(int i = start; i < candidates.size(); i++) {
if((target - candidates[i]) >= 0) {
out.push_back(candidates[i]);
//> start = i, because the same value can be used multi-times
combineByDFS(i, target-candidates[i], candidates, out, ans);
out.pop_back();
}
}
}
}
};

kotlin
class Solution {
fun combinationSum(candidates: IntArray, target: Int): List<List<Int>> {
val ans = mutableListOf<List<Int>>()
dfs(0, candidates, target, emptyList(), ans)
return ans
}
fun dfs(start: Int, candidates: IntArray, target: Int, cmb: List<Int>, ans: MutableList<List<Int>>) {
if (target == 0) {
ans.add(cmb)
return
}
for(i in start..candidates.lastIndex) {
if(target - candidates[i] >= 0) {
dfs(i, candidates, target - candidates[i], cmb+listOf(candidates[i]), ans)
}
}
}
}

沒有留言:

張貼留言