从键盘中输入一个整数n(0<n<=9),要用0至n之间不同的三个数构成一个三位数,编写程序统计这样的数共有几个。

从键盘中输入一个整数n(0<n<=9),要用0至n之间不同的三个数构成一个三位数,编写程序统计这样的数共有几个。

有用请采纳


#include<iostream>
#include<vector>
using namespace std;

class Solution{
private:
    int count;
    int* visited;      // 保存是否被访问过的状态 , 未被访问为0, 被访问之后为1 
    int n;
    vector<int> res;
    
public:
    Solution(int n);
    void getRes();
    void backTracking(vector<int>& temp);
    int getCount();  // 只统计数量 
    void showRes(vector<int>& temp);
};

Solution::Solution(int n){
    count = 0;
    this->n = n;
    visited = new int[n+1];    // 初始化 
    for(int i = 0; i <= n; i++)
        visited[i] = 0;
    
    getRes();   // 执行求结果 
}

int Solution::getCount(){
    return count; 
}

void Solution::backTracking(vector<int>& temp){
    if(temp.size() == 3){
        count += 1;           // 统计个数
//        showRes(temp);        // 可以显示数结果 进行验证 
        return; 
    }
    
    for(int i = 0; i <= n; i++){  // 包含n
        if (temp.size() == 0 && i == 0)  // 首位不为零 
            continue;
        
        if(visited[i] == 0){
            temp.push_back(i);
            visited[i] = 1;
            backTracking(temp);
            temp.pop_back();   // 回溯 
            visited[i] = 0;
        } 
    }
}

void Solution::getRes(){
    vector<int> temp;  // 暂时存放三位数
    backTracking(temp);
}

void Solution::showRes(vector<int>& temp){
    for(int i = 0; i < temp.size(); i++)
        cout << temp[i];
    cout << endl;
}

int main(){
    int n;
    cin >> n;
    Solution s = Solution(n);
    cout << s.getCount() << endl; 
}