本文主要是介绍leetcode No77. Combinations,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Question:
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], ]
Algorithm:
二叉树构造,深度为k,元素为1~n。具体见程序。
Accepted Code:
class Solution {
public:vector<vector<int>> res;vector<vector<int>> combine(int n, int k) {vector<int> temp;BFS(temp,n,1,k);return res;}void BFS(vector<int> &temp,int n,int cur,int k) //cur(1~n){if(temp.size()==k) //如果长度为k,则返回结果{res.push_back(temp);return;}for(int i=cur;i<=n;i++) //遍历cur后到n的元素{vector<int> tmp=temp; tmp.push_back(i);BFS(tmp,n,i+1,k);}}
};
这篇关于leetcode No77. Combinations的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!