【LeetCode】C# 40、Combination Sum II

来源:互联网 发布:sql where in 编辑:程序博客网 时间:2024/05/21 21:37

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.
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]
]
给定无序数组和一目标值,给出其中所有和为目标的子集合。

跟上题一样还是采用的DP思想,递归。还是一样的没在LeetCode AC 因为我不知道IList<IList<int>>如何实例化。

public class Solution {    public List<List<int>> CombinationSum2(int[] candidates, int target) {        Array.Sort(candidates);        List<List<int>> res = new List<List<int>>();        List<int> path = new List<int>();        dfs_com(candidates, 0, target, path, res);        return res;    }    public void dfs_com(int[] candidates, int cur, int target, List<int> path, List<List<int>> res) {        if (target == 0) {            res.Add(new List(path));            return ;        }        if (target < 0) return;        for (int i = cur; i < candidates.Length; i++){            if (i > cur && candidates[i] == candidates[i-1]) continue;            path.Add(path.Count(), candidates[i]);            dfs_com(candidates, i+1, target - candidates[i], path, res);            path.RemoveAt(path.Count()-1);        }    }}
原创粉丝点击