算法設計與分析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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章