[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],
]

Solution:

public class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        List<Integer> temp = new ArrayList<Integer>();
        dfs(n, k, 0, 1, result, temp);
        return result;
    }

    private void dfs(int n, int k, int step, int start, List<List<Integer>> result, List<Integer> temp) {
        // TODO Auto-generated method stub
        if (step > k)
            return;
        if (step == k) {
            result.add(new ArrayList<Integer>(temp));
            return;
        }
        for(int i=start;i<=n;++i){
            temp.add(i);
            dfs(n, k, step+1, i+1, result, temp);
            temp.remove(temp.size()-1);
        }
    }
}
原文地址:https://www.cnblogs.com/Phoebe815/p/4093967.html