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 2,3,6,7 and target 7,
A solution set is:
[7]
[2, 2, 3]
A solution set is:
[7]
[2, 2, 3]
DFS:
public class Solution { public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) { ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> tmp = new ArrayList<Integer>(); Arrays.sort(candidates); comHelp(res, tmp, candidates, target, 0); return res; } private void comHelp(ArrayList<ArrayList<Integer>> res, ArrayList<Integer> tmp, int[] candidates, int target, int index) { if (target < 0) { return; } if (target == 0) { res.add(new ArrayList<Integer>(tmp)); return; } for (int i = index; i < candidates.length; i++) { tmp.add(candidates[i]); comHelp(res, tmp, candidates, target - candidates[i], i); tmp.remove(tmp.size() - 1); } } }
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
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 10,1,2,7,6,1,5 and target 8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
基本思路和permutation2一样,需要一个boolean array来帮助检测重复情况。
public class Solution { //Time: O(n^n) public ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) { ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> tmp = new ArrayList<Integer>(); Arrays.sort(num); boolean[] visit = new boolean[num.length]; combination(res, tmp, num, visit, target, 0); return res; } private void combination(ArrayList<ArrayList<Integer>> res, ArrayList<Integer> tmp, int[] num, boolean[] visit, int target, int index) { if (target < 0) { return; } if (target == 0) { res.add(new ArrayList<Integer>(tmp)); return; } for (int i = index; i < num.length; i++) { if (i != 0 && num[i] == num[i - 1] && !visit[i - 1]) { continue; } tmp.add(num[i]); visit[i] = true; combination(res, tmp, num, visit, target - num[i], i + 1); tmp.remove(tmp.size() - 1); visit[i] = false; } } }
No comments:
Post a Comment