<LeetCode>77. 组合

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

示例:

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

解题思路:1234四个数中,任取两个数组合起来。

可以这么想,1234顺序选取。

首先在4个数中选2个,可以分解为先选取一个,再从三个数中选取一个。

那么递归就能写出来了。

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

猜你喜欢

转载自blog.csdn.net/w8253497062015/article/details/82555615
今日推荐