leetcode -- Combination Sum
2013-08-03 17:26
281 查看
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.
Elements in a combination (a1, a2, � , ak) must be in non-descending order. (ie, a1 ? a2 ? � ? ak).
The solution set must not contain duplicate combinations.
For example, given candidate set
A solution set is:
本题是求解所有可能的组合数,可用DFS来求解,如需求解最优解,需使用DP
DFS的递归函数中只处理当前状态节点n,而不关心它的下一状态
ref:
DFS 算法入门:/article/4073746.html
The same repeated number may be chosen from C unlimited number of times.
Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, � , ak) must be in non-descending order. (ie, a1 ? a2 ? � ? ak).
The solution set must not contain duplicate combinations.
For example, given candidate set
2,3,6,7and target
7,
A solution set is:
[7]
[2, 2, 3]
本题是求解所有可能的组合数,可用DFS来求解,如需求解最优解,需使用DP
DFS的递归函数中只处理当前状态节点n,而不关心它的下一状态
public class Solution { public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) { // Start typing your Java solution below // DO NOT write main() function int len = candidates.length; ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>(); if(len == 0) return results; Arrays.sort(candidates); ArrayList<Integer> result = new ArrayList<Integer>(); int level = 0; int sum = 0; DFS(candidates, level, sum, target, result, results); return results; } public void DFS(int[] candidates, int level, int sum, int target, ArrayList<Integer> result, ArrayList<ArrayList<Integer>> results){ if(sum > target) return; if(sum == target){ ArrayList<Integer> tmp = new ArrayList<Integer>(); tmp.addAll(result); results.add(tmp); return; } if(sum < target){ for(int i = level; i < candidates.length; i++){ sum += candidates[i]; result.add(candidates[i]); DFS(candidates, i, sum, target, result, results); result.remove(result.size() - 1); sum -= candidates[i]; } } } }
ref:
DFS 算法入门:/article/4073746.html
相关文章推荐
- leetcode[39]Combination Sum
- Leetcode: Combination Sum
- Leetcode--Combination Sum
- LeetCode--Combination Sum --ZZ
- leetcode 39-Combination Sum
- leetcode--Combination Sum
- [LeetCode] Combination Sum
- Combination Sum - LeetCode
- leetcode -- Combination Sum
- LeetCode: Combination Sum
- [LeetCode] Combination Sum
- LeetCode--Combination Sum
- 【leetcode】Combination Sum (middle)
- 38 leetcode - Combination Sum
- [leetcode]Combination Sum
- LeetCode – Combination Sum
- Leetcode解题笔记-Combination Sum
- LeetCode - Combination Sum
- leetcode-Combination Sum
- [leetcode]Combination Sum