LeetCode(77)-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],
]
這道題讓求1到n共n個數字裏k個數的組合數的所有情況

public class l77_Combinations {
    ArrayList<ArrayList<Integer>> res=new ArrayList<>();
    ArrayList<Integer> temp=new ArrayList<>();
    public ArrayList<ArrayList<Integer>> combine(int n, int k) {

        dfs(n,k,1);
        return res;
    }

    void dfs(int n,int k,int start){

        if(temp.size()==k)
        //重新創建一個Arraylist對象存儲
            res.add(new ArrayList<Integer>(temp));
        for(int i=start;i<=n;i++){
            temp.add(i);
            dfs(n,k,i+1);
            temp.remove(temp.size()-1);

        }
    }
    public static void main(String[] args) {
        l77_Combinations s=new l77_Combinations();
        Scanner scanner=new Scanner(System.in);
        int n=scanner.nextInt();
        int k=scanner.nextInt();
        ArrayList<ArrayList<Integer>> ans=s.combine(n,k);
        System.out.println(ans);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章