zoukankan      html  css  js  c++  java
  • 77. Combinations

    Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

    For example,
    If n = 4 and k = 2, a solution is:

    [
      [2,4],
      [3,4],
      [2,3],
      [1,2],
      [1,3],
      [1,4],
    ]

    public IList<IList<int>> Combine(int n, int k) {
            var res = new List<IList<int>>();
            BackTracking(res,n,k,1,new List<int>());
            return res;
        }
        
        private void BackTracking(IList<IList<int>> res, int n,int k, int sentinel, IList<int> cur)
        {
            if(k==0) res.Add(new List<int>(cur));
            else
            {
                for(int i = sentinel; i <= n;i++ )
                {
                    cur.Add(i);
                    BackTracking(res,n,k-1,i+1,cur);
                    cur.RemoveAt(cur.Count()-1);
                }
            }
        }
  • 相关阅读:
    第九周学习总结&实验报告(7)
    团队展示
    结对编程
    微信公众号
    编程作业
    《构建之法》
    自我介绍
    java学期总结
    14周作业
    13周总结
  • 原文地址:https://www.cnblogs.com/renyualbert/p/5877862.html
Copyright © 2011-2022 走看看