【leetcode】 c++ 数字全排列, test ok

1. 问题

2. 思路

3. 代码实现

cpp 复制代码
#if 0
class Solution 
{
private:
	vector<int> path;	// 满足条件的一个结果 
	vector<vector<int>> res;	// 结果集 
	
	void backtracking(vector<int> nums, vector<bool> used)
    {
		// 若path的个数和nums个数相等,说明得到一个结果 
		if(path.size() == nums.size())
        {
			res.push_back(path);
			return ;
		}
		
		for(int i = 0; i < nums.size(); i++)
        {
			if(used[i] == true)	// 已经选过,跳过 
            {
				continue;
            }
			used[i] = true;	// 选择 
			path.push_back(nums[i]); // 加入元素 
			backtracking(nums, used); // 进入下一层循环 
			path.pop_back();	// 回溯, 去掉元素 
			used[i] = false; 	// 回溯,撤销选择 
		}
	}
public:
    vector<vector<int>> permute(vector<int>& nums) 
    {
		path.clear();
		res.clear();
		vector<bool> used(nums.size(), false);
		backtracking(nums, used);
		return res;
    }
};
#endif

//效率比较高的代码
///
class Solution {
public:
    vector<vector<int>> permute(vector<int>& nums) 
    {
        dfs(nums, path, res);
        return res;
    }

    void dfs (vector<int> &nums, vector<int> &path, vector<vector<int>> &res)
    {
        // 触发结束条件
        if (path.size() == nums.size()) 
        {
            res.push_back(path);
            return;
        }

        for (vector<int>::size_type i = 0; i < nums.size(); ++i) 
        {
            // 做选择,通过nums和path推测出选择列表
            vector<int>::iterator iter = find(path.begin(), path.end(), nums[i]);
            if (iter != path.end()) 
            { // 如果nums[i]已经出现在path中,则应跳过,否则加到path中(排除不合法选择)
                continue;
            }
            path.push_back(nums[i]);
            // 递归调用
            dfs(nums, path, res);
            // 撤销选择
            path.pop_back();
        }
    }
private:
    vector<int> path; // 一次遍历路径
    vector<vector<int>> res; // 所有符合路径集合
};

4. 测试结果

相关推荐
兮山与8 分钟前
算法3.0
算法
_OP_CHEN10 分钟前
C++基础:(九)string类的使用与模拟实现
开发语言·c++·stl·string·string类·c++容器·stl模拟实现
爱编程的化学家26 分钟前
代码随想录算法训练营第27天 -- 动态规划1 || 509.斐波那契数列 / 70.爬楼梯 / 746.使用最小花费爬楼梯
数据结构·c++·算法·leetcode·动态规划·代码随想录
CoovallyAIHub37 分钟前
告别等待!十条高效PyTorch数据增强流水线,让你的GPU不再"饥饿"
深度学习·算法·计算机视觉
海琴烟Sunshine1 小时前
leetcode 66.加一 python
python·算法·leetcode
数字化顾问1 小时前
C++分布式语音识别服务实践——架构设计与关键技术
c++
智能化咨询1 小时前
C++分布式语音识别服务实践——性能优化与实战部署
c++
rengang661 小时前
09-随机森林:介绍集成学习中通过多决策树提升性能的算法
人工智能·算法·随机森林·机器学习·集成学习
CoovallyAIHub2 小时前
量子计算迎来诺奖时刻!谷歌赢麻了
深度学习·算法·计算机视觉