洛谷P1118数字三角形,

#include <bits/stdc++.h>
using namespace std;
int c[13][13];//杨辉三角
int b[13];//用于排除
int a[13];//输出解答
int n, p;
void dfs(int dep, int s)
{
	if (s > p)
		return;
	if (dep > n)
	{
		if (s == p)
		{
			for (int i = 1; i <= n; i++)
				cout << a[i]<<" ";
			exit(0);
		}
		return;
	}
	for (int i = 1; i <= n; i++)
	{
		if (b[i] == false)
		{
			b[i] = true;
			a[dep] = i;
			dfs(dep + 1, s +i * c[n][dep]);
			b[i] = false;
		}
	}
}
int main()
{
	cin >> n >> p;//输入
	c[1][1] = 1;
	for (int i = 2; i <= n; i++)
		for (int j = 1; j <= i; j++)
			c[i][j] = c[i - 1][j] + c[i - 1][j - 1];//生成杨辉三角
	dfs(1, 0);
}

深度搜索的使用,关键就是想不到这个杨辉三角的表示,说实话做到这里就不是Mali的问题了。

int main()
{
    int num = 1,a[6]= {1,2,3,4,5};
    while(next_permutation(a,a+5))
    {
        for(int i=0; i<5; i++)
            cout<<a[i]<<" ";
        if(num==5)
            break;
        num++;
        cout<<endl;
    }
    return 0;
}

next_permutation函数:若存在其他的排列,则返回真。直到整个序列降序排序为止。

原文地址:https://www.cnblogs.com/lwt99/p/14145895.html