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
}
相关推荐
圣殿骑士-Khtangc1 小时前
Go字符串高效拼接性能对比与底层原理分析
服务器·前端·golang
旖旎夜光2 小时前
LeetCode 3:无重复字符的最长子串(滑动窗口) —— 题解
数据结构·c++·算法·leetcode·滑动窗口
Navigator_Z5 小时前
LeetCode //C - 1192. Critical Connections in a Network
c语言·算法·leetcode
rannn_1115 小时前
【力扣hot100】链表专题下|138、148、23、146
java·算法·leetcode·链表·开发
xzlAwin5 小时前
Win10安装Go语言多版本管理器g工具
开发语言·golang
hanlin036 小时前
刷题笔记:力扣第189题-轮转数组
笔记·算法·leetcode
琥珀色糖6 小时前
leetcode hot100题(持续更新)移动零(双指针)
算法·leetcode·职场和发展·双指针·移动零
hanlin037 小时前
动态规划专练:力扣第718、1143题
算法·leetcode·动态规划
FfHUCisI10 小时前
Golang RESTful API 设计原则
开发语言·golang·restful
hanlin0312 小时前
动态规划专练:力扣第1035、392题
算法·leetcode·动态规划