Using recursion and backtracking to generate all possible combinations

前端 未结 3 532
孤城傲影
孤城傲影 2020-12-14 05:02

I\'m trying to implement a class that will generate all possible unordered n-tuples or combinations given a number of elements and the size of the combination.

In ot

3条回答
  •  一个人的身影
    2020-12-14 05:08

    In MATLAB:

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% combinations.m
    
    function combinations(n, k, func)
    assert(n >= k);
    n_set = [1:n];
    k_set = zeros(k, 1);
    recursive_comb(k, 1, n_set, k_set, func)
    return
    
    function recursive_comb(k_set_index, n_set_index, n_set, k_set, func)
    if k_set_index == 0,
      func(k_set);
      return;
    end;
    for i = n_set_index:length(n_set)-k_set_index+1,
      k_set(k_set_index) = n_set(i);
      recursive_comb(k_set_index - 1, i + 1, n_set, k_set, func); 
    end;
    return;
    
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    
    Test:
    >> combinations(5, 3, @(x) printf('%s\n', sprintf('%d ', x)));
    3 2 1 
    4 2 1 
    5 2 1 
    4 3 1 
    5 3 1 
    5 4 1 
    4 3 2 
    5 3 2 
    5 4 2 
    5 4 3 
    

提交回复
热议问题