matlab从一个数组[1,2,3,4,5,6,7,8,9,10,11]中一共选取t个元素,分n次选完,i=1:n。在第i次选取时,选取k(i)个元素。在第i+1次选取时,在剩下的未选取的元素之中选取k(i+1)个值,以此类推。然后将从选取数组中选取的元素按选取顺序组成一个新的数组,遍历所有可能性
25条回答 默认 最新
关注
获得0.30元问题酬金 function combinations = generate_combinations(arr, t, n, k) combinations = cell(1, n); generate_combinations_recursive(arr, t, n, k, 1, [], combinations); end function generate_combinations_recursive(arr, t, n, k, i, current_combination, combinations) if i > n combinations{end} = [combinations{end}; current_combination]; return; end for j = 1:t-k(i)+1 new_combination = [current_combination, arr(j)]; generate_combinations_recursive(arr(j+1:end), t-k(i), n, k, i+1, new_combination, combinations); end end
在 MATLAB 中调用这个函数并传入相应的参数,如下所示:
arr = [1,2,3,4,5,6,7,8,9,10,11]; t = 5; % 选取的元素个数 n = 3; % 分次选取的次数 k = [2, 3]; % 每次选取的元素个数 combinations = generate_combinations(arr, t, n, k);
解决 1无用