Skip to content

Latest commit

 

History

History
101 lines (79 loc) · 1.8 KB

77.组合.md

File metadata and controls

101 lines (79 loc) · 1.8 KB

77. 组合

url

题目

给定两个整数 nk,返回 1 ... n 中所有可能的 k 个数的组合。

输入: n = 4, k = 2
输出:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

方法

code

js

let combine = (n, k) => {
    let res = [];
    let dfs = (list, start, k, n) => {
        if (k === 0) {
            res.push(list.slice());
            return
        }
        for (let i = start; i <= n - k + 1; i++) {
            list.push(i);
            dfs(list, i + 1, k - 1, n);
            list.pop();
        }
    }
    dfs([], 1, k, n);
    return res
}

go

func combine(n, k int) [][]int {
	var res [][]int
	var dfs func(list []int, start, k, n int)
	dfs = func(list []int, start, k, n int) {
		if k == 0 {
			res = append(res, append([]int{}, list...))
			return
		}
		for i := start; i <= n-k+1; i++ {
			list = append(list, i)
			dfs(list, i+1, k-1, n)
			list = list[0:len(list)-1]
		}
	}
	dfs([]int{}, 1, k, n)
	return res
}

java

class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> combinations = new ArrayList<>();
        List<Integer> combineList = new ArrayList<>();
        backtracking(combineList, combinations, 1, k, n);
        return combinations;
    }
    private void backtracking(List<Integer> combineList, List<List<Integer>> combinations, int start, int k, final int n) {
        if (k == 0) {
            combinations.add(new ArrayList<>(combineList));
            return;
        }
        for (int i = start; i <= n - k + 1; i++) {
            combineList.add(i);
            backtracking(combineList, combinations, i + 1, k - 1, n);
            combineList.remove(combineList.size() - 1);
        }
    }
}