leetcode 题解代码整理 36-40题

Valid Sudoku

Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.

The Sudoku board could be partially filled, where empty cells are filled with the character ‘.‘.

A partially filled sudoku which is valid.

判断数独当前状态是否合法

class Solution
{
public:
    bool isValidSudoku(vector<vector<char>>& board)
    {
        int col[10][10],row[10][10],box[10][10];
        int i,j,x,a;
        memset(col,0,sizeof(col));
        memset(row,0,sizeof(row));
        memset(box,0,sizeof(box));
        for (i=0;i<9;i++)
            for (j=0;j<9;j++)
                if (board[i][j]!='.')
                {
                    x=board[i][j]-'0';
                    a=i/3*3+j/3;
                    if (row[i][x]==1 || col[j][x]==1 || box[a][x]==1) return false;
                    else row[i][x]=col[j][x]=box[a][x]=1;
                }

        return true;
    }
};

Sudoku Solver

Write a program to solve a Sudoku puzzle by filling the empty cells.

Empty cells are indicated by the character ‘.‘.

You may assume that there will be only one unique solution.

A sudoku puzzle...

...and its solution numbers marked in red.

DFS解数独,保证唯一解

class Solution
{
int col[10][10],row[10][10],box[10][10];

public:
    void solveSudoku(vector<vector<char> >& board)
    {
        memset(col,0,sizeof(col));
        memset(row,0,sizeof(row));
        memset(box,0,sizeof(box));
        for (int i=0;i<9;i++)
            for (int j=0;j<9;j++)
            if (board[i][j]!='.')
            {
                col[j][board[i][j]-'0']=1;
                row[i][board[i][j]-'0']=1;
                box[i/3*3+j/3][board[i][j]-'0']=1;
            }

        dfs(board,0);
    }

    bool dfs(vector<vector<char> > & board,int key)
    {
        int i,j;
        if (key==81) return true;
        int x=key/9;
        int y=key%9;
        if (board[x][y]!='.')
            return dfs(board,key+1);
        else
        {
            int a=x/3*3+y/3;
            for (int i=1;i<=9;i++)
            if (col[y][i]==0 && row[x][i]==0 && box[a][i]==0)
            {
                col[y][i]=row[x][i]=box[a][i]=1;
                board[x][y]=i+'0';
                if (dfs(board,key+1)) return true;
                col[y][i]=row[x][i]=box[a][i]=0;
                board[x][y]='.';
            }
        }
        return false;

    }
};

Count and Say

The count-and-say sequence is the sequence of integers beginning as follows:

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

1 is read off as "one
1"
 or 11.

11 is read off as "two
1s"
 or 21.

21 is read off as "one
2
, then one 1" or 1211.

Given an integer n, generate the nth sequence.

Note: The sequence of integers will be represented as a string.

模拟过程

class Solution
{
public:
    string countAndSay(int n)
    {
        vector<int>mark[n+1];
        int temp;
        char ch;
        mark[1].push_back(1);
        string ans;
        int i,sum,j;

        for (i=2;i<=n;i++)
        {
            temp=mark[i-1][0];
            sum=1;
            for (j=1;j<mark[i-1].size();j++)
            if (mark[i-1][j]!=temp)
            {
                mark[i].push_back(sum);
                mark[i].push_back(temp);
                temp=mark[i-1][j];
                sum=1;
            }
            else    sum++;

            mark[i].push_back(sum);
            mark[i].push_back(temp);
        }
        ans="";
        for (i=0;i<mark[n].size();i++)
        {
            ch=mark[n][i]+'0';
            ans=ans+ch;
        }
        return ans;

    }
};

Combination Sum

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where
the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1, a2,
    … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤
    … ≤ ak).
  • The solution set must not contain duplicate combinations.

For example, given candidate set 2,3,6,7 and target 7,

A solution set is:

[7]

[2, 2, 3]

输出序列中和=target的种类,可重复使用

Combination Sum II

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where
the candidate numbers sums to T.

Each number in C may only be used once in the combination.

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1, a2,
    … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤
    … ≤ ak).
  • The solution set must not contain duplicate combinations.

For example, given candidate set 10,1,2,7,6,1,5 and target 8,

A solution set is:

[1, 7]

[1, 2, 5]

[2, 6]

[1, 1, 6]

同上题,加一个条件,出现的数只能使用一次

class Solution
{
vector<vector<int> >ans;
vector<int>num;
int key;
int len;
private:
void dfs(vector<int>mark,int n,int sum,int used)
{

    if (sum==key)
    {
        ans.push_back(mark);
        return ;
    }
    if (n==len) return ;
    if (sum+num[n]>key) return ;
    dfs(mark,n+1,sum,0);
    if (num[n]==num[n-1] && used==0) return ;

    mark.push_back(num[n]);
    dfs(mark,n+1,sum+num[n],1);
    mark.pop_back();

}
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target)
{
    len=candidates.size();
    num=candidates;
    sort(num.begin(),num.end());
    key=target;

    vector<int>mark;
    dfs(mark,0,0,1);
    return ans;
}
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-11-03 20:59:04

leetcode 题解代码整理 36-40题的相关文章

leetcode 题解代码整理 1-5题

Two Sum Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please no

leetcode 题解代码整理 31-35题

Next Permutation Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending orde

leetcode 题解代码整理 21-25题

Merge Two Sorted Lists Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. 合并两个有序链表 /** * Definition for singly-linked list. * struct ListNode { * int val; * Li

leetcode 题解代码整理 6-10题

ZigZag Conversion The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line

【题解整理】二分题

[题解整理]二分题 题目类型: 二分查找: 二分答案. 大致解题思路: 查找注意有序和返回值: 浮点数注意精度: 整数注意返回值,建议另外维护一个变量,用于储存可行解. 题目 分类 传送门 WA点 poj 2785 二分查找 题解 lightoj 1088 二分查找 题解 lightoj 1307 二分查找 题解 longlong poj 2456 整数二分答案 题解 poj 3104 整数二分答案 题解 poj 3258 整数二分答案 题解 poj 3273 整数二分答案 题解 lightoj

【LeetCode】树(共94题)

[94]Binary Tree Inorder Traversal [95]Unique Binary Search Trees II (2018年11月14日,算法群) 给了一个 n,返回结点是 1 - n 的所有形态的BST. 题解:枚举每个根节点 r, 然后递归的生成左右子树的所有集合,然后做笛卡尔积. 1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *

[LeetCode]题解(python):031-Next Permutation

题目来源 https://leetcode.com/problems/next-permutation/ Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible

leetcode题解:Binary Tree Postorder Traversal (二叉树的后序遍历)

题目: Given a binary tree, return the postorder traversal of its nodes' values. For example:Given binary tree {1,#,2,3}, 1 2 / 3 return [3,2,1]. Note: Recursive solution is trivial, could you do it iteratively? 说明: 1) 两种实现,递归与非递归 , 其中非递归有两种方法 2)复杂度分析:时

leetcode题解:Tree Level Order Traversal II (二叉树的层序遍历 2)

题目: Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). For example:Given binary tree {3,9,20,#,#,15,7}, 3 / 9 20 / 15 7 return its bottom-up level order tr