[LeetCode]Combinations

来源:互联网 发布:mac屏幕截图保存位置 编辑:程序博客网 时间:2024/06/07 11:23

题目

Number: 77
Difficulty: Medium
Tags: Backtracking

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],]

题解

给出两个整数k和n,在1...n中找出所有k个数的组合。

用回溯法求解。

代码

vector<vector<int>> combine(int n, int k) {    vector<vector<int>> res;    if(n < k) return res;    vector<int> ans;    com(res, ans, n, k, 0);    return res;}void com(vector<vector<int>> &res, vector<int> &ans, int n, int k, int start) {    if(ans.size() == k){        res.push_back(ans);        return;    }    for(int i = start; i < n; i++){        ans.push_back(i + 1);        com(res, ans, n, k, i + 1);        ans.pop_back();    }}
0 0
原创粉丝点击