【leetcode】77. Combinations C(n,k)的所有组合形式

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
    原文地址: https://segmentfault.com/a/1190000007407186
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞