码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode---回溯法(全排列)

时间:2020-06-08 13:05:47      阅读:64      评论:0      收藏:0      [点我收藏+]

标签:leetcode   lag   phi   ace   head   回溯法   etc   超过   ble   




#46 全排列

https://leetcode-cn.com/problems/permutations/submissions/

给定一个 没有重复 数字的序列,返回其所有可能的全排列。

class Solution {
public:

vector<vector<int>> result;
vector<int> temp;
int flag[1000] = {0};

vector<vector<int>> permute(vector<int>& nums)
{
    Dfs(nums,0,nums.size());

    return result;
}

void Dfs(vector<int>& nums,int index,int length)
{
	//退出条件
    if(index >= length){
        result.push_back(temp);
        return;
    }

	//回溯
    for(int i=0;i<length;i++){
        if(!flag[i]){
            temp.push_back(nums[i]);
            flag[i] = 1;
            Dfs(nums,index+1,length);
            temp.pop_back();
            flag[i] = 0;
        }
    }
}

};

#1415 长度为 n 的开心字符串中字典序第 k 小的字符串

https://leetcode-cn.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/


class Solution {
public:

//判断到了第几个
int cnt = 0;
//中间字符串
string temp;
//需要返回第k个字符串
string ret;

void Dfs(int n,int k,int index)
{
    //超过第k个,退出
    if(cnt >= k){
        return ;
    }


    //超过字符串最大位数,退出
    if(index == n){
        cnt++;
        ret = temp;
        cout<<ret<<endl;
        return ;
    }


    //回溯
    for(int i = ‘a‘;i<=‘c‘;i++){
        //限定条件
        if(index && temp.back() ==i){
            continue;
        }

        temp.push_back(i);
        Dfs(n,k,index+1);
        temp.pop_back();
    }
}



string getHappyString(int n, int k)
{
    Dfs(n,k,0);
    return cnt==k?ret:"";
}

};

一道之前笔试遇到的全排列题目

题目大概是:
输入n,k
比如输入123 6
求123的全排列中能被6整除的个数。

#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>

using namespace std;

char flag[11];
//判断有几个可以整除
int cnt = 0;
//中间字符串
string temp = "";

int Str2Int(string str)
{
    int ret = 0;
    for(int i=str.size()-1; i>=0; i--)
    {
        ret += (str[i]-48)*pow(10,str.size()-i-1);
    }
    return ret;
}

void Dfs(string str,int k,int index)
{
    //超过字符串最大位数
    if(index >= str.size())
    {
        cout<<temp<<endl;
        int num = Str2Int(temp);
        if(num%k==0)
            cnt++;

        return ;
    }

    int j = 0;
    //可能的值
    for(char i = str[j]; j<str.size(); i=str[++j])
    {
        if(!flag[j])
        {
            temp.push_back(i);
            flag[j] = true;
            Dfs(str,k,index+1);
            flag[j] = false;
            temp.pop_back();
        }
    }
}

int Cal(string n, int k)
{
    Dfs(n,k,0);

    return cnt;
}

int main()
{
    string str;
    int k;
    cin>>str;
    cin>>k;

    cout<<Cal(str,k);

    return 0;

}


LeetCode---回溯法(全排列)

标签:leetcode   lag   phi   ace   head   回溯法   etc   超过   ble   

原文地址:https://www.cnblogs.com/Fflyqaq/p/13064884.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!