Golang | Leetcode Golang题解之第77题组合

题目:

题解:

Go 复制代码
func combine(n int, k int) (ans [][]int) {
	// 初始化
	// 将 temp 中 [0, k - 1] 每个位置 i 设置为 i + 1,即 [0, k - 1] 存 [1, k]
	// 末尾加一位 n + 1 作为哨兵
	temp := []int{}
	for i := 1; i <= k; i++ {
		temp = append(temp, i)
	}
	temp = append(temp, n+1)

	for j := 0; j < k; {
		comb := make([]int, k)
		copy(comb, temp[:k])
		ans = append(ans, comb)
		// 寻找第一个 temp[j] + 1 != temp[j + 1] 的位置 t
		// 我们需要把 [0, t - 1] 区间内的每个位置重置成 [1, t]
		for j = 0; j < k && temp[j]+1 == temp[j+1]; j++ {
			temp[j] = j + 1
		}
		// j 是第一个 temp[j] + 1 != temp[j + 1] 的位置
		temp[j]++
	}
	return
}
相关推荐
Elias不吃糖16 分钟前
克隆图(LeetCode 133)——用数组做映射的 DFS 解法
c++·算法·leetcode·深度优先
小白程序员成长日记42 分钟前
力扣每日一题 2025.11.30
数据结构·算法·leetcode
u***28471 小时前
golang debug调试
开发语言·后端·golang
CoderYanger1 小时前
递归、搜索与回溯-穷举vs暴搜vs深搜vs回溯vs剪枝:13.子集
java·算法·leetcode·机器学习·剪枝·1024程序员节
疯疯癫癫才自由1 小时前
爬取Leetcode Hot 100 题单
算法·leetcode
CoderYanger1 小时前
递归、搜索与回溯-综合练习:28.不同路径Ⅲ
java·算法·leetcode·深度优先·1024程序员节
T0uken2 小时前
Go + Node.js 全栈单文件部署方案
golang·node.js·状态模式
小画家~2 小时前
第三十四:golang 原生 pgsql 对应操作
android·开发语言·golang
捧 花2 小时前
Go语言模板的使用
golang·go·template method·模板·web app
希望有朝一日能如愿以偿2 小时前
力扣每日一题:使数组和能被p整除
数据结构·算法·leetcode