题目链接:https://leetcode.com/problems/combinations/
这是一条组合数学题的组合问题,最终结果有个。跟前面的组合排列问题相似的套路:用一个全局变量保存所有答案,用一个定长数组一个答案,递归参数idx表示上一次递归已经取过的数字,本次递归可以选择的数应该从大于idx的数中去选择。
class Solution {
public static List<List<Integer>> ret;
public static int[] record;
public List<List<Integer>> combine(int n, int k) {
ret=new LinkedList<>();
record=new int[k];
recursive(0,k,n);
return ret;
}
public static void recursive(int idx,int k,int n)
{
if(k==0)
{
LinkedList<Integer> tmp=new LinkedList<>();
for(int i=record.length-1;i>=0;i--)
tmp.add(record[i]);
ret.add(tmp);
return;
}
for(int j=idx+1;j<=n;j++)
{
record[k-1]=j;
recursive(j,k-1,n);
}
}
}
效率杠杠的!!!