組合

組給出兩個整數n和k,返回從1......n中選出的k個數的組合。

樣例

例如 n = 4 且 k = 2

返回的解爲:

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


按順序來取數,如 n = 4 且 k = 2,先取1,再在2,3,4裏面取一個數,1作爲開始的取完後,將1拋棄,從2開始取,直到取完所有的。


class Solution {
public:
    /**
     * @param n: Given the range of numbers
     * @param k: Given the numbers of combinations
     * @return: All the combinations of k numbers out of 1..n
     */
    vector<vector<int> > combine(int n, int k) {
        // write your code here
        vector<vector<int> > a2;
        vector<int> a1;
        solve(1,1,n,k,a1,a2);
        return a2;
    }
    
    void solve(int num, int start, int n, int k, vector<int> &a1,vector<vector<int> > &a2)
    {
        if(num == k)
        {
            for(int i = start; i <=n; i++)
            {
                a1.push_back(i);
                a2.push_back(a1);
                a1.erase(--a1.end());
            }
            return;
        }
        
        for(int i = start; i <=n; i++)
        {
            a1.push_back(i);
            solve(num+1, i+1, n, k, a1, a2);
            a1.erase(--a1.end());
        }
    }

};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章