1. 题目

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],
]

2. 思路

递归的完成,从n个里选择k个。有两种情况,一种是先选择第一个,然后从剩下的里面选择k-1个;另一种是不选第一个,从剩下的里面选择k个。

直接用递归居然没有超时...好无聊

3. 代码

耗时:146ms

class Solution {
public:
    vector<vector<int>> combine(int n, int k) {
        return combine(n, k, 1);
    }
    
    vector<vector<int>> combine(int n, int k, int start) {
        vector<vector<int>> ret;
        if (k == 1) {
            for (int i = start; i <= n; i++) {
                vector<int> one;
                one.push_back(i);
                ret.push_back(one);
            }
            return ret;
        } else if (n < k || n-start+1 < k) { return ret; }
        
        vector<vector<int>> left1 = combine(n, k-1, start+1);
        for (int i = 0; i < left1.size(); i++) {
            left1[i].push_back(start);
            ret.push_back(left1[i]);
        }
        vector<vector<int>> left2 = combine(n, k, start+1);
        for (int i = 0; i < left2.size(); i++) { ret.push_back(left2[i]);}
        return ret;
    }
};

knzeus
72 声望28 粉丝

行万里路,读万卷书