19.2.15 [LeetCode 77] Combinations

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

Example:

Input: n = 4, k = 2
Output:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

题意

在1到n中取k个数的所有情况

题解

 1 class Solution {
 2 public:
 3     void build(vector<vector<int>>&ans,vector<int>&now, int n, int k) {
 4         if (k == 0) {
 5             ans.push_back(now);
 6             return;
 7         }
 8         int s = 0;
 9         if (!now.empty())s = now.back();
10         for (int i = s + 1; i <= n - k + 1; i++) {
11             now.push_back(i);
12             build(ans, now, n, k - 1);
13             now.pop_back();
14         }
15     }
16     vector<vector<int>> combine(int n, int k) {
17         vector<vector<int>>ans;
18         vector<int>now;
19         build(ans, now, n, k);
20         return ans;
21     }
22 };
View Code
posted @ 2019-02-15 15:45  TobicYAL  阅读(117)  评论(0编辑  收藏  举报