算法练习

组合(LeetCode 77,与78,90属于一类)

2020-02-20  本文已影响0人  倚剑赏雪

题目

给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]

解析

1.解法同78
2.当子List添加时首先判断是否等于K,等于K添加并跳出

public IList<IList<int>> Combine(int n, int k) {
        IList<IList<int>> res = new List<IList<int>>();
        BackTrackK(1,n,k,res,new List<int>());
        return res;
    }

    void BackTrackK(int idx,int max ,int len,IList<IList<int>> res, IList<int> temp)
    {
        if (temp.Count == len)
        {
            res.Add(new List<int>(temp));
            return;
        }
        for (int i = idx; i <= max; i++)
        {
            temp.Add(i);
            BackTrackK(i+1,max,len,res,temp);
            temp.RemoveAt((temp.Count-1));
        }
    }
上一篇 下一篇

猜你喜欢

热点阅读