题解 | #加起来和为目标值的组合#

加起来和为目标值的组合

https://www.nowcoder.com/practice/172e6420abf84c11840ed6b36a48f8cd

using System;
using System.Collections.Generic;


class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param target int整型
     * @param nums int整型一维数组
     * @return int整型二维数组
     */
    public List<List<int>> combinationCount (int target, List<int> nums) {
        // write code here
        if (nums.Count == 0 || target == 0)
            return new List<List<int>>();
        List<List<int>> lslsN = new List<List<int>>();
        List<int> lsN = new List<int>();
        DG(target, nums, lslsN, 0, lsN);
        return lslsN;
    }

    public void DG(int target, List<int> nums, List<List<int>> lslsN, int nCurR,
                   List<int> lsN) {
        for (int i = 0; i < nums.Count; i++) {
            if (nCurR + nums[i] > target)
                continue;
            List<int> lsNT = new List<int>();
            lsNT.AddRange(lsN);
            lsNT.Add(nums[i]);
            if (nCurR + nums[i] == target) {
                lsNT.Sort();
                int nFindIndex = lslsN.FindIndex(r => string.Join("", r).Equals(string.Join("",
                                                 lsNT)));
                if (nFindIndex == -1)
                    lslsN.Add(lsNT);
                continue;
            }
            DG(target, nums, lslsN, nCurR + nums[i], lsNT);
        }
    }
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务