【LeetCode】77. Combinations

题目:

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

Example:

Input: n = 4, k = 2
Output:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

描述:

给出n和k,输出 1 - n,k个数字的所有组合 

 

分析:

递归打印,跟打印全排列类似的方法,但是需要加上判断,只允许正序,

可惜好像没有现成的函数可以调用...

 

代码:(时间复杂度指数级别)

class Solution {
public:
	vector<vector<int>> combine(int n, int k) {
		vector<bool> visit(n, 0);
		vector<vector<int>> result;
		vector<int> current;
		dfs(k, current, visit, result);
		return result;
	}
	
	void dfs(int k, vector<int> &current, vector<bool> &visit, vector<vector<int>> &result) {
		
		if (!k) {
			result.push_back(current);
			return ;
		}
		for (int i = current.size(); i < visit.size(); ++ i) {
			if (!visit[i]) {
				visit[i] = 1;
				if (!current.size() || i >=  current[current.size() - 1]) {
					current.push_back(i + 1);
					dfs(k - 1, current, visit, result);
					current.pop_back();
				}
				visit[i] = 0;
			}
		}
	}
};

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页