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

]

 

Hide Tags
  Backtracking  

链接:  http://leetcode.com/problems/combinations/

题解:

求组合数。依然是使用recursive + backtracking,当所传list的大小等于k时,将list加入到result里。使用控制位置的变量pos根据题目要求从1开始,本体依然假定无重复数字。 

Time Complexity - O(2n), Space Complexity - O(n)。                         --复杂度有点糊涂,还需要重新计算

public class Solution {

    public ArrayList<ArrayList<Integer>> combine(int n, int k) {

        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();

        if(n < 0 || k < 0)

            return result;

        ArrayList<Integer> list = new ArrayList<Integer>();

        helper(result, list, n, k, 1);

        return result;

    }

    

    private void helper(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> list, int n, int k, int pos){

        if(list.size() == k){

            result.add(new ArrayList<Integer>(list));

            return;

        }

        

        for(int i = pos; i <= n; i++){

            list.add(pos);

            helper(result, list, n, k, ++pos);

            list.remove(list.size() - 1);

        }

    }

}

 

测试:

Reference:

http://codeganker.blogspot.com/2014/03/combinations-leetcode.html

http://www.cnblogs.com/zhuli19901106/p/3485751.html

http://www.1point3acres.com/bbs/thread-117602-1-1.html

你可能感兴趣的:(com)