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],
]
Solution:
采用位运算来做,但是这样时间复杂度很高O(n* 2^ n)。
 1 public class Solution {
 2     public ArrayList<ArrayList<Integer>> combine(int n, int k) {
 3         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
 6         for(int i = 0; i < Math.pow(2,n); i ++){
 7             ArrayList<Integer> row = new ArrayList<Integer>();
 8             for(int j = 0; j < n; j ++){
 9                 if((i >> j & 1)  == 1){
10                     row.add(j + 1);
11                 } 
12             }
13             if(row.size() == k)
14                 result.add(row);
15         }
16         return result;
17     }
18 }

 第二遍: 使用递归。过不了大循环。

 1 public class Solution {
 2     ArrayList<ArrayList<Integer>> result = null;
 3     public ArrayList<ArrayList<Integer>> combine(int n, int k) {
 4         // Start typing your Java solution below
 5         // DO NOT write main() function
 6         result = new ArrayList<ArrayList<Integer>>();
 7         boolean[] map = new boolean[n];
 8         getAnswer(map, new ArrayList<Integer>(), k);
 9         return result;
10     }
11     public void getAnswer(boolean[] map, ArrayList<Integer> row, int n){
12         if(n == 0) result.add(row);
13         for(int i = 0; i < map.length; i ++){
14             if(!map[i]){
15                 map[i] = true;
16                 row.add(i + 1);
17                 getAnswer(map, row, n - 1);
18                 map[i] = false;
19             }
20         }
21     }
22 }

 

posted on 2013-10-01 14:42  Step-BY-Step  阅读(149)  评论(0编辑  收藏  举报

导航