Skip to content

Instantly share code, notes, and snippets.

@Chen-tao
Last active January 28, 2017 08:54
Show Gist options
  • Save Chen-tao/23e658e72ab8d0860f7d06345dabcbb1 to your computer and use it in GitHub Desktop.
Save Chen-tao/23e658e72ab8d0860f7d06345dabcbb1 to your computer and use it in GitHub Desktop.
//https://leetcode.com/problems/combinations/
// 深度优先搜索框架
public class Solution {
public static List<List<Integer>> ans = new ArrayList<List<Integer>>();
public static int[] path = new int[100];
public static int K = 0;
public static void robot(int idx, int n, int k){//idx [0, n]
if(k == 0){//choose end
//record ans
List<Integer> tmp = new ArrayList<Integer>();
for(int i=K - 1; i >=0 ;i--){
tmp.add(path[i]);
}
ans.add(tmp);
return;
}
for(int i = idx + 1; i<=n; i++){//下一层搜索的范围, 如果单调, 则要比idx大
path[k - 1] = i;
robot(i, n, k - 1);
}
}
public List<List<Integer>> combine(int n, int k) {
ans.clear();
K = k;
robot(0, n, k);
return ans;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment