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
}
相关推荐
学历真的很重要2 小时前
Claude Code 万字斜杠命令指南
后端·语言模型·面试·职场和发展·golang·ai编程
萘柰奈2 小时前
LeetCode刷题记录----62.不同路径(Medium)
算法·leetcode·职场和发展
会跑的葫芦怪4 小时前
Go语言net/http库使用详解
http·golang·iphone
自信的小螺丝钉7 小时前
Leetcode 146. LRU 缓存 哈希表 + 双向链表
leetcode·缓存·散列表
数据知道13 小时前
Go基础:Go语言能用到的常用时间处理
开发语言·后端·golang·go语言
2351615 小时前
【LeetCode】3. 无重复字符的最长子串
java·后端·算法·leetcode·职场和发展
微笑尅乐16 小时前
神奇的位运算——力扣136.只出现一次的数字
java·算法·leetcode·职场和发展
自信的小螺丝钉16 小时前
Leetcode 155. 最小栈 辅助栈
leetcode·
吃着火锅x唱着歌16 小时前
LeetCode 3105.最长的严格递增或递减子数组
算法·leetcode·职场和发展
吃着火锅x唱着歌17 小时前
LeetCode 2765.最长交替子数组
算法·leetcode·职场和发展