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
}
相关推荐
圣保罗的大教堂1 小时前
leetcode 3736. 最小操作次数使数组元素相等 III 简单
leetcode
文丑颜不良啊2 小时前
LeetCode1881~1990题目解析
java·leetcode
文丑颜不良啊5 小时前
LeetCode1861~1880题目解析
java·leetcode
文丑颜不良啊5 小时前
LeetCode1921~1940题目解析
java·leetcode
一去不复返的通信er8 小时前
排序 + 双指针:力扣15三数之和
算法·leetcode
文丑颜不良啊8 小时前
LeetCode1901~1920题目解析
java·leetcode
Pniubi8 小时前
力扣3无重复字符的最长字串(滑动窗口)
算法·leetcode·职场和发展
Zenova EdgeOS20 小时前
Go 工业边缘错误处理实战:用 errors 构建可追溯错误链
开发语言·数据库·golang
JavaPub-rodert1 天前
从零搭建通用管理后台:ShiyuAdmin 的 Go、React 与 RBAC 实践
开发语言·react.js·golang
microrain1 天前
SagooIoT 的数据接入层只有四张表,却能接住三种外部数据
物联网·golang·数据建模·sagooiot