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

题目:

题解:

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. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-05-12 16:52:05       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-12 16:52:05       106 阅读
  3. 在Django里面运行非项目文件

    2024-05-12 16:52:05       87 阅读
  4. Python语言-面向对象

    2024-05-12 16:52:05       96 阅读

热门阅读

  1. PostgreSQL自带的命令行工具10- pg_basebackup

    2024-05-12 16:52:05       38 阅读
  2. Linux上的监控工具:Zabbix、Prometheus、APM和ELK

    2024-05-12 16:52:05       31 阅读
  3. SSL VPN

    SSL VPN

    2024-05-12 16:52:05      31 阅读
  4. 2024.5.12 ubuntu + latex + vscode

    2024-05-12 16:52:05       33 阅读
  5. springboot Redis 支持星号(*) 包括注解@Cache

    2024-05-12 16:52:05       31 阅读
  6. Oracle一键安装脚本安装教程合集

    2024-05-12 16:52:05       35 阅读
  7. SSH简介:网络安全的守护者

    2024-05-12 16:52:05       37 阅读
  8. 对Promise的理解

    2024-05-12 16:52:05       32 阅读
  9. 【C++】引用传递 & 常量引用

    2024-05-12 16:52:05       36 阅读