lintcode-152-组合

152-组合

组给出两个整数n和k,返回从1......n中选出的k个数的组合。

样例

例如 n = 4 且 k = 2
返回的解为:
[[2,4],[3,4],[2,3],[1,2],[1,3],[1,4]]

标签

回溯法 数组

思路

使用回溯和递归

code

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
        if (n <= 0 || k <= 0) {
            return vector<vector<int> >();
        }

        vector<vector<int> > result;
        vector<int> temp;
        isInsert(result, temp, 1, n, k);
        return result;
    }

    void isInsert(vector<vector<int> > &result, vector<int> &temp, int current, int n, int k) {
        if (temp.size() == k) {
            result.push_back(temp);
            return;
        }
        if (current <= n) {
            temp.push_back(current);
            isInsert(result, temp, current+1, n, k);
            temp.pop_back();
            isInsert(result, temp, current + 1, n, k);
        }
    }
};
posted @ 2017-07-30 16:45  LiBaoquan  阅读(460)  评论(0编辑  收藏  举报