leetcode 77 Combinations
阿新 • • 發佈:2018-12-26
Given two integers n and k, return all possible combinations of knumbers out of 1 ... n.
Example:
Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
這是一道常規的dfs題,之前也對相應的題進行過訓練,可惜好幾天不刷,動手的時候又不知道該怎麼寫了。由於沒什麼特殊性,且題目和46題全排列基本類似,這裡直接上程式碼,記錄一下。
class Solution { public: vector<vector<int>> combine(int n, int k) { vector<vector<int>> ret; vector<int> tmp; dfsCombine(ret, tmp, n, k, 1); return ret; } void dfsCombine(vector<vector<int>> &ret, vector<int> &tmp, int n, int k, int start) { if(tmp.size() == k) { ret.push_back(tmp); return; } for(int i = start; i <= n; i++) { tmp.push_back(i); dfsCombine(ret, tmp, n, k, i+1); tmp.pop_back(); } } };