lintcode-medium-Combination Sum II
Posted 哥布林工程师
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode-medium-Combination Sum II相关的知识,希望对你有一定的参考价值。
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in Cwhere the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Notice
- 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.
Given candidate set [10,1,6,7,2,1,5]
and target 8
,
A solution set is:
[
[1,7],
[1,2,5],
[2,6],
[1,1,6]
]
public class Solution { /** * @param num: Given the candidate numbers * @param target: Given the target number * @return: All the combinations that sum to target */ public List<List<Integer>> combinationSum2(int[] num, int target) { // write your code here List<List<Integer>> result = new ArrayList<List<Integer>>(); if(num == null || num.length == 0) return result; List<Integer> line = new ArrayList<Integer>(); boolean[] visited = new boolean[num.length]; Arrays.sort(num); helper(result, line, num, target, visited, 0); return result; } public void helper(List<List<Integer>> result, List<Integer> line, int[] num, int target, boolean[] visited, int start){ if(target < 0) return; if(target == 0){ result.add(new ArrayList<Integer>(line)); return; } for(int i = start; i < num.length; i++){ if(i > 0 && num[i] == num[i - 1] && !visited[i - 1]) continue; line.add(num[i]); visited[i] = true; helper(result, line, num, target - num[i], visited, i + 1); line.remove(line.size() - 1); visited[i] = false; } return; } }
以上是关于lintcode-medium-Combination Sum II的主要内容,如果未能解决你的问题,请参考以下文章