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 小时前
吃透栈:LeetCode 栈算法题全解析
数据结构·c++·算法·leetcode·职场和发展·
阿Y加油吧2 小时前
二刷 LeetCode:62. 不同路径 & 64. 最小路径和 复盘笔记
笔记·算法·leetcode
研究点啥好呢2 小时前
滴滴Go后端开发工程师面试题精选:10道高频考题+答案解析
java·开发语言·golang
承渊政道2 小时前
【动态规划算法】(两个数组的DP问题深度剖析与求解方法)
数据结构·c++·学习·算法·leetcode·动态规划·哈希算法
加农炮手Jinx2 小时前
LeetCode 26. Remove Duplicates from Sorted Array 题解
算法·leetcode·力扣
加农炮手Jinx2 小时前
LeetCode 88. Merge Sorted Array 题解
算法·leetcode·力扣
阿Y加油吧2 小时前
二刷 LeetCode:75. 颜色分类 & 31. 下一个排列 复盘笔记
笔记·算法·leetcode
NEGl DRYN3 小时前
Go基础之环境搭建
开发语言·后端·golang
初心未改HD3 小时前
Go Modules:依赖管理的完全指南
开发语言·golang
小雅痞3 小时前
[Java][Leetcode middle] 3. 无重复字符的最长子串
java·开发语言·leetcode