LeetCode-combinations

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

For example,
If n = 4 and k = 2, a solution is:

[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]
import java.util.ArrayList;
public class Solution { 
    public ArrayList<ArrayList<Integer>> combine(int n, int k) { 
        ArrayList<ArrayList<Integer>> result = new ArrayList<>(); 
        combine(n, k, 1, result, new ArrayList<>()); 
        return result; 
    } 
   
    public void combine(int n, int k, int start, ArrayList<ArrayList<Integer>> result, ArrayList<Integer> l) { 
        if(k == 0) { 
            result.add(l); 
            return; 
        } 
        for(int i = start; i <= n; ++i) { 
            ArrayList<Integer> a = new ArrayList<>(l); 
            a.add(i); 
            combine(n, k - 1, i + 1, result, a); 
        } 
    } 
}

 

上一篇:javascript – 没有sort()的组合算法


下一篇:javascript – 查找在一定范围内加起来为X的N个非重复数字的所有可能组合