LeetCode 77. Combinations

Given two integers n and k , return all possible combinations ofnumbers chosen from the range[1, n].

You may return the answer in any order.

Example 1:

Input: n = 4, k = 2
Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
Explanation: There are 4 choose 2 = 6 total combinations.
Note that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination.

Example 2:

Input: n = 1, k = 1
Output: [[1]]
Explanation: There is 1 choose 1 = 1 total combination.

解析:此题目类似于LeetCode 78. Subsets ,只不过限制集合的数量大小为k,稍作修改即可。

class Solution {
public:
    vector<vector<int>> combine(int n, int k) {
        vector<vector<int>> result;
        vector<int> ans;
        backtrace(result, ans, 1, n, k);
        return result;
    }

    void backtrace(vector<vector<int>>& result, vector<int>& ans, int index, int n, int k){
        if(ans.size() == k){
            result.push_back(ans);
            return;
        }
        for(int i = index; i <= n; i++){
            ans.push_back(i);
            backtrace(result, ans, i+1, n, k);
            ans.pop_back();
        }
    }
};

Add a Comment

邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据