77. Combinations**

来源:互联网 发布:语义搜索python 编辑:程序博客网 时间:2024/04/30 12:27

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],]
My code:

public class Solution {    public List<List<Integer>> combine(int n, int k) {        List<List<Integer>> result = new ArrayList<List<Integer>>();        backtrack(result, new ArrayList<Integer>(),n,k,1);        return result;    }    private void backtrack(List<List<Integer>> list, List<Integer> tempList, int n, int k, int start){        if(k==0) list.add(new ArrayList(tempList));        else{            for(int i= start;i<=n&&k>0;i++){                tempList.add(i);                backtrack(list, tempList, n, k-1, i+1);                tempList.remove(tempList.size()-1);            }        }    }}
总结:自己完成的,完美。还是熟能生巧。



0 0
原创粉丝点击