77. Combinations

77. Combinations

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

Example:

Input: n = 4, k = 2
Output:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

My Solutions:

和subset类似,但把temp加入result的条件是长度等于k,并且满足条件直接返回。

class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> list = new ArrayList<>();
        dfs(list, new ArrayList<Integer>(), n, k, 1);
        return list;
    }
    
    public void dfs(List<List<Integer>> list, List<Integer> temp, int n, int k, int start) {
        
        if (temp.size() == k) {
            list.add(new ArrayList<Integer>(temp));
            return; // 满足条件直接返回
        }
        
        for (int i = start; i <= n; i++){
            temp.add(i);
            dfs(list, temp, n, k, i + 1);
            temp.remove(temp.size() - 1);
        }
    }
}

Last updated