1. 程式人生 > >[leetcode]77. Combinations

[leetcode]77. Combinations

[leetcode]77. Combinations


Analysis

waiting~—— [每天刷題並不難0.0]

Given two integers n and k, return all possible combinations of k numbers out of 1 … n.
在這裡插入圖片描述
排列和組合的問題好像一般都可以用遞迴來解決~

Implement

class Solution {
public:
    vector<vector<int>> combine(int n, int k) {
        vector<
int> tmp; helper(tmp, 1, n, k); return res; } void helper(vector<int>& tmp, int start, int n, int k){ if(k == 0){ res.push_back(tmp); return ; } for(int i=start; i<=n; i++){ tmp.push_back(i); helper(
tmp, i+1, n, k-1); tmp.pop_back(); } } private: vector<vector<int>> res; };