leetcode题目例题解析(十一)

leetcode题目例题解析(十一)

Combinations

题目描述:

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

题意解析:

一个排列组合的问题

解题思路:

利用递归,比较容易解决

代码:

class Solution {
public:
    vector<vector<int>> ans;
    vector<vector<int>> combine(int n, int k) {
        vector<int> temp;
        find(n, k, 0, 0 , temp);
        return ans;
    }
    void find(int n, int k, int deep, int last, vector<int> temp) {
        if (temp.size() == k) {
            ans.push_back(temp);
        } else if (deep <= n&&temp.size() < k) {
            vector<int> t;
            for (int i = last + 1; i <= n; i++) {
                t = temp;
                t.push_back(i);
                find(n, k, deep + 1, i, t);
            }
        }
    }
};

原题目链接:
https://leetcode.com/problems/combinations/description/

猜你喜欢

转载自blog.csdn.net/OzhangsenO/article/details/78680703
今日推荐