回溯排列数组合数完全解答

//全排列数->部分排列数->///(部分)组合数:好像不对///
//myprint->取全排列前n个->部分排列数基础上加上单调验证
#include <iostream>
#include <vector>
#include <stack>
#include <set>
#include <string>
#include <algorithm>
using namespace std;
void myprint(vector<int> &a,int i) {
	if (i == a.size() - 1) {
		for (int i = 0; i < 3;i++) {
			cout << a[i] << ',';
		}
		cout << endl;
		//return;
	}
	else {
		for (int k = i; k < a.size();k++) {
			swap(a[k], a[i]);
			myprint(a, i + 1);
			swap(a[k], a[i]);
		}	
	}
}
===================================================================================================================
//此程序为标准组合数
void fun(vector<vector<int>>& ans, vector<int>& tmp,int index,int k,int n) {
    if (tmp.size() == k) {
        ans.push_back(tmp);
        return;
    }
    for (int i = index; i < n;i++) {
        tmp.push_back(i+1);
        fun(ans, tmp, i+1, k, n);
        tmp.pop_back();
    }
}
vector<vector<int>> combine(int n, int k) {
    vector<vector<int>> ans;
    vector<int> tmp;
    fun(ans, tmp, 0,k,n);
    return ans;
}
posted @ 2021-11-18 20:09  Zupernova  阅读(44)  评论(0编辑  收藏  举报