1 条题解

  • 0
    @ 2025-10-10 15:45:59

    C++ :

    #include <bits/stdc++.h>
    using namespace std;
    int a[100010] = {0};
    int n;
    int r; 
    bool b[100010];//标记该数是否用过
    
    void show(){
    	int i;
    	for(i = 1;i <= r;i++){
    		cout<<a[i]<<" ";
    	}
    	cout<<endl;
    } 
    
    //回溯找数 
    int search(int k){
    	int i;
    	for(i = 1;i <= n;i++){
    		//如果i没用过 
    		if(b[i] == false){
    			a[k] = i;//结果存入数组 
    			b[i] = true;//标记为用过
    			//够数量,输出结果 
    			if(k == r){
    				show();
    			} else{
    				//继续找数
    				search(k + 1); 
    			}
    			//回溯
    			b[i] = false;//标记该数没用过 
    		}
    	}
    } 
    
    int main(){
    	cin>>n>>r;
    	search(1);
    }
    
    

    Python :

    import math
    import sys
    n,r=list(map(int,input().split()))
    
    vis=[0]*(n+1)
    a=[0]*(n+1)
    
    def df(step):
        if step>r:
            for item in a[1:1+r]:
                print(item,end=" ")
            print()
            return 
        for i in range(1,n+1):
            if vis[i]==0:
                a[step]=i
                vis[i]=1
                df(step+1)
                vis[i]=0
    df(1)
    
    
    • 1

    信息

    ID
    341
    时间
    1000ms
    内存
    256MiB
    难度
    (无)
    标签
    递交数
    0
    已通过
    0
    上传者