【LeetCode31-40】全排列,栈的用法,find用法,数独规则及解法,数列,类似找钱问题找出所有可能,不允许重复的找钱问题


31.找出全排列的下一个序列

1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1


全排序:地址

例如一个全排列如下(要计算一个排列的下一个全排列)

1,2,3
1,3,2
2,1,3
2,3,1
3,2,1
3,1,2
解决方法一:

class Solution {
public:
	void nextPermutation(vector<int>& nums) {	    
	    next_permutation(nums.begin(),nums.end());//上一个是std::prev_permutation

	}

};

解决方法二:

class Solution {
public:
    void nextPermutation(vector<int> &num) 
    {
        if (num.empty()) return;
        
        // in reverse order, find the first number which is in increasing trend (we call it violated number here)
        int i;
        for (i = num.size()-2; i >= 0; --i)
        {
            if (num[i] < num[i+1]) break;
        }
        
        // reverse all the numbers after violated number
        reverse(begin(num)+i+1, end(num));
        // if violated number not found, because we have reversed the whole array, then we are done!
        if (i == -1) return;
        // else binary search find the first number larger than the violated number
        auto itr = upper_bound(begin(num)+i+1, end(num), num[i]);
        //返回一个比num[i]大的最小的……简直作弊……
        // swap them, done!
        swap(num[i], *itr);
    }
};


32. Longest Valid Parentheses【有空需要再看看!!!!】

找出字符串里符合逻辑最长的长度……



Stack用法:

c++ stl栈stack的成员函数介绍

操作 比较和分配堆栈

empty() 堆栈为空则返回真

pop() 移除栈顶元素

push() 在栈顶增加元素

size() 返回栈中元素数目

top() 返回栈顶元素


class Solution {
public:
    int longestValidParentheses(string s) {
        stack<int>temp;
        temp.push(-1);//push操作往栈里加一项
        int result=0;
        for(int i=0;i<s.size();i++){
            if(temp.top()!=-1&&s[temp.top()]=='('&&s[i]==')'){
                temp.pop();
                result=max(result,i-temp.top());//这里没有+1因为已经pop掉了,也是赋值-1的作用
                
            }
            else{
                temp.push(i);
            }
        }
        return result;
    }
};

/*class Solution {
//失败了,超时了
public:
    int longestValidParentheses(string s) {
        int result=2*(s.size()/2);
        bool goon=true;
        if(s.size()<2)return 0;
        while(goon){
        goon=false;
        for(int i=0;i<s.size()-result+1;i++){
            if(isvalid(s.substr(i,result))){return result;}
        }
        result-=2;goon=true;
        if(result==0)goon=false;
        }
       return result; 
    }
    bool isvalid(string s){
        int left=0,right=0;
        for(int i=0;i<s.size();i++){
            if(s[i]=='(')left++;
            else right++;
            if(right>left)return false;
        }
        if(right!=left)return false;
        return true;
    }
};*/


33.找到一个循环升序序列里的指定数字位置

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

二分法检索(binary search)又称折半检索,二分法检索的基本思想是设字典中的元素从小到大有序地存放在数组(array)中。


解法一:find函数

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int result=-1;
    vector<int>::iterator location = find( nums.begin( ), nums.end( ), target ); //查找target
    if ( location == nums.end( ) ) //没找到
        return -1;
    result=location-nums.begin();
    return result;
    
    }
};

解法二:看成两个sorted序列的组合……采用binary search(二分法查找)


class Solution {
public:
    int search(int A[], int n, int target) {
        int lo=0,hi=n-1;
        // find the index of the smallest value using binary search.
        // Loop will terminate since mid < hi, and lo or hi will shrink by at least 1.
        // Proof by contradiction that mid < hi: if mid==hi, then lo==hi and loop would have been terminated.
        while(lo<hi){
            int mid=(lo+hi)/2;
            if(A[mid]>A[hi]) lo=mid+1;
            else hi=mid;
        }
        // lo==hi is the index of the smallest value and also the number of places rotated.
        int rot=lo;
        lo=0;hi=n-1;
        // The usual binary search and accounting for rotation.
        while(lo<=hi){
            int mid=(lo+hi)/2;
            int realmid=(mid+rot)%n;
            if(A[realmid]==target)return realmid;
            if(A[realmid]<target)lo=mid+1;
            else hi=mid-1;
        }
        return -1;
    }
};

  

34.找出sorted序列里指定数字所在位置(开始和结束位置)

解决方法(只是为了熟悉下迭代器,这个方法并不好,是O(n),如果想log(n)就需要二分法查找了)

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        int begin=-1;
        vector<int>::iterator it=nums.begin();
        for(;it<nums.end();++it){
            if(*it==target){begin=it-nums.begin();break;}
            
        }
        int end=begin;
        if(begin==-1){}
        else{
        while(end!=nums.size()-1&&nums[end+1]==target){
            end++;
        }
        }
        vector<int>result;
        result.push_back(begin);
        result.push_back(end);
        return result;
    }
};


35.找到在sorted数组里的插入位置  

//要注意+1。。。。

二分法查找,因为可以插入到头和尾,所以放宽到-1以及nums.size()……就假设这两个位置为无穷小和无穷大……

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        //插入到一个顺序排列,这回找不到理由不用二分法查找了……
        int begin=-1,end=nums.size();
        int result=(begin+end+1)/2;
        while(begin<end-1){
            if(nums[result]>target)end=result;
            if(nums[result]==target)return result;
            if(nums[result]<target)begin=result;
            result=(begin+end+1)/2;
        }
        return result;
    }
};

另一种写法的二分法:(不用放宽到-1到end()了)

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int low = 0, high = nums.size()-1;

        // Invariant: the desired index is between [low, high+1]
        while (low <= high) {
            int mid = low + (high-low)/2;

            if (nums[mid] < target)
                low = mid+1;
            else
                high = mid-1;
        }

        // (1) At this point, low > high. That is, low >= high+1
        // (2) From the invariant, we know that the index is between [low, high+1], so low <= high+1. Follwing from (1), now we know low == high+1.
        // (3) Following from (2), the index is between [low, high+1] = [low, low], which means that low is the desired index
        //     Therefore, we return low as the answer. You can also return high+1 as the result, since low == high+1
        return low;
    }
};


36.检测数独是否合法

(不用全填满,只要检测有的部分……即便真的不能填也算true)


class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        //检测行
        bool result;
        for(int i=0;i<9;i++){
            if(!isvalid(board[i]))return false;
        }
        //检测列
        for(int i=0;i<9;++i){
            vector<char>temp;
            for(int j=0;j<9;++j){
                temp.push_back(board[j][i]);
            }
            if(!isvalid(temp))return false;
        }
        //检测块
          for(int i=0;i<9;++i){
            vector<char>temp;
            int begin1=i%3*3;
            int begin2=i/3*3;
            
            for(int j=0;j<9;++j){
                temp.push_back(board[begin2+j/3][begin1+j%3]);
            }
            if(!isvalid(temp))return false;
        }      
        return true;
    }
    bool isvalid(vector<char>&temp){
        unordered_map<char,int>mapping;
        for(int i=0;i<9;++i){
            mapping[temp[i]];
            if(++mapping[temp[i]]>1&&temp[i]!='.')return false;
        }
        return true;
    }
};


别人的非常简洁的方法:

used1代表行,used2代表列,used3代表方块

class Solution
{
public:
    bool isValidSudoku(vector<vector<char> > &board)
    {
        int used1[9][9] = {0}, used2[9][9] = {0}, used3[9][9] = {0};
        
        for(int i = 0; i < board.size(); ++ i)
            for(int j = 0; j < board[i].size(); ++ j)
                if(board[i][j] != '.')
                {
                    int num = board[i][j] - '0' - 1, k = i / 3 * 3 + j / 3;
                    if(used1[i][num] || used2[j][num] || used3[k][num])
                        return false;
                    used1[i][num] = used2[j][num] = used3[k][num] = 1;
                }
        
        return true;
    }
};



37.解数独【参考了别人的解法】

迭代迭代迭代……总觉得效率好低……(参考了别人的解法)

class Solution {
public:
    void solveSudoku(vector<vector<char>>& board) {
        sove(board,0,0);
    }
    
    bool sove(vector<vector<char>>& board,int i,int j){
        if(i==9)return true;
        if(j==9)return sove(board,i+1,0);//{j=0;++i;}
        if(board[i][j]!='.')return sove(board,i,j+1);
        

        for(int ii=1;ii<10;ii++){
            if(check(board, i, j, '0'+ii)){
                    board[i][j]='0'+ii;         
                    if(sove(board,i,j+1))return true;
                    board[i][j]='.';
                }
        }
        
        return false;
    }
    
    bool check(vector<vector<char>> &board, int i, int j, char val)
{
    int row = i - i%3, column = j - j%3;
    for(int x=0; x<9; x++) if(board[x][j] == val) return false;
    for(int y=0; y<9; y++) if(board[i][y] == val) return false;
    for(int x=0; x<3; x++)
    for(int y=0; y<3; y++)
        if(board[row+x][column+y] == val) return false;
    return true;
}
    
};


38.数和说 //返回数组第n个数字

每个数是读前一个数字的结果,例如1个1,2个1。。。。

1, 11, 21, 1211, 111221, ...


class Solution {
public:
    string countAndSay(int n) {
        string result="1";
        for(int i=1;i<n;i++){
            result=count(result);
        }
        return result;

    }
    string count(string n){
        string result="";
        string temp=n;
        for(int i=0;i<temp.size();++i){
            int answer=1;
            while(i+1<temp.size()&&temp[i]==temp[i+1]){
                ++answer;
                ++i;
           }
            
        result+=to_string(answer);
        result+=temp[i];
        }

        return result;
    }
}; 

39.找出所有和的可能//迭代,挺经典,可以再看看

For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:

[
  [7],
  [2, 2, 3]
]

用到了DP搜索,类似于518题。。。

然后利用了string存储,如果直接用vector<vector<int>>会超出内存允许范围……


(利用X以及Y插入标定位置。。感觉好蠢……)


class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& coins, int amount) {
        unordered_map<int,string>mapping;
        mapping[0]="X";
    for(int i=0;i<coins.size();i++){  
    for(int j=coins[i];j<=amount;j++) {
        string temp=mapping[j-coins[i]];
       
       int size=temp.size();
        for(int ii=0;ii<temp.size();++ii){
            if(temp[ii]=='X'){temp.insert(ii,to_string(coins[i])+"Y");
            ii+=temp.size()-size;
            size=temp.size();
            }
        }
        
        mapping[j]+=temp;

    }
    }  
    vector<vector<int>>result;
    string temp=mapping[amount];
    int begin=0;
    for(int i=0;i<temp.size();++i){
        if(temp[i]=='X'){
            vector<int>one;
            int begin1=begin;
            for(int j=begin;j<i;j++){
                if(temp[j]=='Y'){
                 one.push_back(atoi(temp.substr(begin1,j-begin1).c_str()));
                 begin1=j+1;
                }
            }
            result.push_back(one);
            begin=i+1;
        }
    }
    return result;  
        
    }
};
别人的迭代的方法:
class Solution {
public:
    std::vector<std::vector<int> > combinationSum(std::vector<int> &candidates, int target) {
        std::sort(candidates.begin(), candidates.end());
        std::vector<std::vector<int> > res;
        std::vector<int> combination;
        combinationSum(candidates, target, res, combination, 0);
        return res;
    }
private:
    void combinationSum(std::vector<int> &candidates, int target, std::vector<std::vector<int> > &res, std::vector<int> &combination, int begin) {
        if (!target) {
            res.push_back(combination);
            return;
        }
        for (int i = begin; i != candidates.size() && target >= candidates[i]; ++i) {
            combination.push_back(candidates[i]);
            combinationSum(candidates, target - candidates[i], res, combination, i);
            combination.pop_back();
        }
    }
};

40.找出所有和的可能,但不允许无限次使用,出现多少次允许几次

参考了上一题


做题经验总结:

STL的函数不能直接vector.XXX()

例如reverse,sort等等

vector查找函数find(XX.begin(),XX.end()),Sth)==XX.end()表示有没有找到

类型::iterator it=find(XX.begin(),XX.end()),Sth)  //迭代器的用法


迭代的用法还需要再训练训练

class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        sort(candidates.begin(),candidates.end());//注意用法!!
        //试试用迭代好了
        vector<vector<int>>result;
        vector<int>temp;
        sove(result,temp,target,candidates,0);
        return result;
    }
private:
     void sove(vector<vector<int>>&result,vector<int>&temp,int target,vector<int>& candidates,int begin){
         if(target==0){
             if(find(result.begin(),result.end(),temp)==result.end())//找出重复的
                result.push_back(temp);
             return;
             
         }
         if(target<0)return;
         
        // if(candidates.size()==0)return;
         
         for(int i=begin;i<candidates.size()&&target-candidates[0]>=0;i++){
             
             temp.push_back(candidates[i]);
             sove(result,temp,target-candidates[i],candidates,i+1);//i+1很重要,表示只一次
             temp.pop_back();

      //       sove(result,temp,target,candidates);
         }
     //   return;
     }
     
};





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

朱铭德

五毛也是爱٩(●´৺`●)૭

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值