1209. 带分数 一道挺好的搜索题 c++ java
100 可以表示为带分数的形式:100=3+69258714
还可以表示为:100=82+3546197
注意特征:带分数中,数字 1∼9 分别出现且只出现一次(不包含 0)。
类似这样的带分数,100 有 11 种表示法。
输入格式
一个正整数。
输出格式
输出输入数字用数码 1∼9 不重复不遗漏地组成带分数表示的全部种数。
数据范围
1≤N<106
输入样例1:
100
输出样例1:
11
输入样例2:
105
输出样例2:
6
c++
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int N=30;
int st[N],tmp[N];
int ans,n;
bool check(int a,int c)
{
long long b=(long long)n*c-a*c; //c最高9位,n最高10^…6所以可能爆int
if(a==0||c==0||b==0)return false;
//for(int i=1;i<=9;++i)tmp[i]=st[i];
memcpy(tmp,st,sizeof(st));
while(b)
{
int x=b%10;
b/=10;
if(x==0||tmp[x]==1)return false;
tmp[x]=1;
}
for(int i=1;i<=9;++i)
{
if(tmp[i]==0)return false;
}
return true;
}
void dfs_c(int u,int a,int c)
{
if(u>=9)return;
if(check(a,c))ans++;
for(int i=1;i<=9;++i)
{
if(st[i]==0)
{
st[i]=1;
dfs_c(u+1,a,c*10+i);
st[i]=0;
}
}
}
void dfs_a(int u,int a)//u表示当前使用过的位数,a表示当前a的值
{
if(a>n)return;
if(a!=0)dfs_c(u,a,0);
for(int i=1;i<=9;++i)
{
if(st[i]==0)
{
st[i]=1;
dfs_a(u+1,a*10+i);
st[i]=0;
}
}
}
int main()
{
cin>>n;
dfs_a(0,0);
cout<<ans;
return 0;
}
java
import java.util.*;
public class Main
{
static long n,ans,st[]=new long [12];
public static void main(String [] args)
{
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
dfs_a(0,0);
System.out.println(ans);
}
static void dfs_a(int u,int a)
{
if(a>n)return ;
if(a!=0)dfs_c(u,a,0);
for(int i=1;i<=9;++i)
{
if(st[i]==0)
{
st[i]=1;
dfs_a(u+1,a*10+i);
st[i]=0;
}
}
}
static void dfs_c(int u,int a,int c)
{
if(u>=9)return ;
if(c!=0&&check(a,c))ans++;
for(int i=1;i<=9;++i)
{
if(st[i]==0)
{
st[i]=1;
dfs_c(u+1,a,c*10+i);
st[i]=0;
}
}
}
static boolean check(int a,int c)
{
long b=n*c-a*c;
if(b==0)return false;
long tmp[]=new long [20];
tmp=Arrays.copyOf(st, 10);
while(b>0)
{
int x=(int)(b%10);
b/=10;
if(x==0||tmp[x]==1)return false;
tmp[x]=1;
}
for(int i=1;i<=9;++i)
{
if(tmp[i]==0)return false;
}
return true;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】