LeetCode 077 Combinations

来源:互联网 发布:知乎 日本留学 编辑:程序博客网 时间:2024/05/22 15:32
题目


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


代码


1 典型的DFS,直接上代码

public class Solution {    public ArrayList<ArrayList<Integer>> combine(int n, int k) {        ArrayList<Integer> temp = new ArrayList<Integer>();        ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();        useme(ans,temp,1,n,k);        return ans;    }        public void useme(ArrayList<ArrayList<Integer>> ans, ArrayList<Integer> temp, int start, int n,int k){        if(k==0){            ans.add(new ArrayList<Integer>(temp));            return;        }        for(int i = start;i<=n;i++){            temp.add(i);            useme(ans,temp,i+1,n,k-1);            temp.remove(temp.size()-1);        }    }}


0 0
原创粉丝点击