【leetcode】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],
]

題解如下:

class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> tmp = new ArrayList<>();
        backtrack(res,tmp,n,k,0);
        return res;
    }
    
    public void backtrack(List<List<Integer>> res,List<Integer> tmp,
                         int n,int k,int idx) {
        if(tmp.size() == k) {
            res.add(new ArrayList(tmp));
            return;
        }
        for(int i = idx;i < n;i++) {
            int num = i + 1;
            tmp.add(num);
            backtrack(res,tmp,n,k,i+1);
            tmp.remove(tmp.size()-1);
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章