您的位置:首页 > 其它

蓝桥杯 历届试题 扑克序列

2016-03-05 15:36 253 查看
A A 2 2 3 3 4 4, 一共4对扑克牌。请你把它们排成一行。

要求:两个A中间有1张牌,两个2之间有2张牌,两个3之间有3张牌,两个4之间有4张牌。

请填写出所有符合要求的排列中,字典序最小的那个。


例如:22AA3344 比 A2A23344 字典序小。当然,它们都不是满足要求的答案。

请通过浏览器提交答案。“A”一定不要用小写字母a,也不要用“1”代替。字符间一定不要留空格。

递归

换成字符串处理比较复杂,就直接先把A当做1,输出结果后不要忘记换过来。

package holiday;

import java.util.Scanner;
import java.util.Vector;

public class A {

public static int a[]={1,2,3,4};
public static int b[]=new int [8];
public static void main(String args[])
{
for(int i=0;i<8;i++)
{
b[i]=0;
}
fun(0);
}
public static void fun(int n)
{
for(int i=0;i<8;i++)
{
if(b[i]==0&&(i+a
+1)<8&&b[i+a
+1]==0)
{
b[i]=b[i+a
+1]=a
;
if(n==3)
{
for(int j=0;j<8;j++)
{
System.out.print(b[j]+" ");
}
System.out.println();
}
else fun(n+1);
b[i]=b[i+a
+1]=0;
}
}
}

}


4 1 3 1 2 4 3 2

2 3 4 2 1 3 1 4

把1换成A,选择较小的字典序即可。

另外,看有人这样写

其中int find(char c, int pos = 0) const;//从pos开始查找字符c在当前字符串的位置

while(next_permutation(s.begin(), s.end()))用于字符数组字典序的全排列,详细用法查看/article/9640622.html

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main(void) {
string s = "223344AA";
do {
unsigned iab = s.find("A", 0);
unsigned iae = s.find("A", iab + 1);
unsigned i2b = s.find("2", 0);
unsigned i2e = s.find("2", i2b + 1);
unsigned i3b = s.find("3", 0);
unsigned i3e = s.find("3", i3b + 1);
unsigned i4b = s.find("4", 0);
unsigned i4e = s.find("4", i4b + 1);
if(iae - iab == 2 && i2e - i2b == 3 && i3e - i3b == 4 && i4e - i4b == 5) {
cout << s << endl;
}

} while(next_permutation(s.begin(), s.end()));
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: