算法设计与分析HW5:LeetCode77

Description:

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

Note:

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

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

 

Solution:

  Analysis and Thinking:

  通过观察给出的example可知,可以用递归来实现,递归过程中需要记录返回结果的容器以及当前数位,当数位达到k位时,则完成单个数字的组合,并把其放入result容器当中,直至所有组合的可能性被遍历。

  Steps:

  1.判断当前数位curPos是否等于k,若是,则把记录当前单个组合的容器numPath加入结果容器result当中,并把此单个组合从单个组合记录容器当中移除。

   2.若当前数位小于k,则从开始位置startPos开始,直至数字n,每次向单个组合容器加入一个1~n的整数,再把开始位置与当前数位加1后,递归调用函数

  3.当递归调用的函数的计数位达到k,跳至1.


Codes:

class Solution
{

public:
    static vector<vector<int> > Combination(int n,int k)
    {

        vector<vector<int> >result;
        vector<int> numPath;
        Combine_DFS(n,k,1,0,numPath,result);
        return result;
    }
    static void Combine_DFS(int n,int k,int startPos,int curPos,vector<int> &numPath,vector<vector<int> >&result)
    {
        if(curPos==k)
        {

            result.push_back(numPath);
        }
        for(int i=startPos;i<=n;i++)
        {

            numPath.push_back(i);
            Combine_DFS(n,k,i+1,curPos+1,numPath,result);
            numPath.pop_back();
        }

    }
};


Results:


发布了35 篇原创文章 · 获赞 0 · 访问量 4641
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章