LeetCode 77. Combinations

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

You may return the answer in any order.

Example 1:

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

Example 2:

Input: n = 1, k = 1
Output: [[1]]

Constraints:

1 <= n <= 20
1 <= k <= n

实现思路:

回溯法,只不过每一次要进入下一层的时候要递增+1.

AC代码:

class Solution {
		vector<vector<int>> ans;
		vector<int> sq;
		bool vist[30]= {0};
		void dfs(int idx,int n,int k) {
			if(sq.size()==k) {
				ans.push_back(sq);
				return;
			}
			for(int i=idx+1; i<=n; i++) {
				if(!vist[i]) {
					vist[i]=true;
					sq.push_back(i);
					dfs(i,n,k);
					vist[i]=false;
					sq.pop_back();
				}
			}
		}

	public:
		vector<vector<int>> combine(int n, int k) {
			dfs(0,n,k);
			return ans;
		}
};
posted @   coderJ_ONE  阅读(33)  评论(0编辑  收藏  举报
编辑推荐:
· 电商平台中订单未支付过期如何实现自动关单?
· 用 .NET NativeAOT 构建完全 distroless 的静态链接应用
· 为什么构造函数需要尽可能的简单
· 探秘 MySQL 索引底层原理,解锁数据库优化的关键密码(下)
· 大模型 Token 究竟是啥:图解大模型Token
阅读排行:
· 瞧瞧别人家的限流,那叫一个优雅!
· 1.net core 工作流WorkFlow流程(介绍)
· 一文彻底搞懂 MCP:AI 大模型的标准化工具箱
· 面试官:如果某个业务量突然提升100倍QPS你会怎么做?
· .NET 平台上的开源模型训练与推理进展
点击右上角即可分享
微信分享提示