本文共 708 字,大约阅读时间需要 2 分钟。
给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2输出:[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4],]
思路:dfs,前面做过好多类似的题目了。
深搜来做。
1、如果得到的当前元素个数等于k,返回。
2、每一层往下搜索的时候,从这个数的后面开始进行搜索。
class Solution {public: void dfs(vector>&re, vector temp, int k, int n, int index){ if(temp.size()==k){ re.push_back(temp); return; } for(int i=index; i<=n; ++i){ temp.push_back(i); dfs(re, temp, k, n, i+1); temp.pop_back(); } } vector > combine(int n, int k) { vector >re; vector temp; dfs(re, temp, k,n, 1); return re; }};
转载地址:http://heabi.baihongyu.com/