LeetCode (P)

Pow(x, n)

  Total Accepted: 5493  Total Submissions: 21464 My Submissions

Implement pow(xn).

class Solution {
    double power(double x, long long n) {
        if (n < 0) return 1 / power(x, -n);
        if (n == 0) return 1;
        double t = power(x, n >> 1);
        if ((n&1) == 0)
            return t * t;
        else
            return t * t * x;
    }
public:
    double pow(double x, int n) {
        return power(x, (long long)n);
    }
};







Plus One

  Total Accepted: 4617  Total Submissions: 15448 My Submissions

Given a number represented as an array of digits, plus one to the number.

class Solution {
public:
    vector<int> plusOne(vector<int> &digits) {
        reverse(digits.begin(), digits.end());
        digits[0] += 1;
        int i = 0;
        while (i < digits.size() && digits[i] > 9) {
            digits[i] = 0;
            if (i == digits.size() - 1)
                digits.push_back(1);
            else
                digits[i + 1] += 1;
            ++i;
        }
        reverse(digits.begin(), digits.end());
        return digits;
    }
};




Partition List

  Total Accepted: 4070  Total Submissions: 15645 My Submissions

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *partition(ListNode *head, int x) {
        ListNode *root1 = new ListNode(0), *root2 = new ListNode(0);
        ListNode *p = head, *q1 = root1, *q2 = root2;
        while (p != NULL) {
            if (p->val < x)
                q1->next = p, q1 = p;
            else
                q2->next = p, q2 = p;
            p = p->next;
        }
        q1->next = root2->next;
        q2->next = NULL;
        p = root1->next;
        delete root1;
        delete root2;
        return p;
    }
};





Palindrome Number

  Total Accepted: 5464  Total Submissions: 18876 My Submissions

Determine whether an integer is a palindrome. Do this without extra space.

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0) return false;
        int rev = 0, t = x;
        while (t)
            rev = rev * 10 + t % 10, t /= 10;
        return (rev == x);
    }
};




Permutation Sequence

  Total Accepted: 2901  Total Submissions: 14159 My Submissions

The set [1,2,3,…,n] contains a total of n! unique permutations.

By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):

  1. "123"
  2. "132"
  3. "213"
  4. "231"
  5. "312"
  6. "321"

Given n and k, return the kth permutation sequence.

Note: Given n will be between 1 and 9 inclusive.

class Solution {
public:
    string getPermutation(int n, int k) {
        string ans;
        --k;
        vector<bool> f(n, false);
        long long s = 1;
        for (int i = 1; i < n; ++i) s *= i;
        for (int i = 0; i < n; ++i) {
            int t = k / s;
            int j = 0, c = 0;
            while (c <= t) {
                if (!f[j]) ++c;
                ++j;
            }
            f[j - 1] = true;
            ans += ('0' + j);
            k %= s;
            if (i != n - 1) s /= (n - 1 - i);
        }
        return ans;
    }
};





Pascal's Triangle

  Total Accepted: 4784  Total Submissions: 15136 My Submissions

Given numRows, generate the first numRows of Pascal's triangle.

For example, given numRows = 5,
Return

[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]
class Solution {
public:
    vector<vector<int> > generate(int numRows) {
        vector<vector<int> > res;
        for (int n = 0; n < numRows; ++n) {
            vector<int> a(n + 1, 1);
            for (int m = 1; m <= n; ++m)
                a[m] = a[m - 1] * (n - m + 1) / m;
            res.push_back(a);
        }
        return res;
    }
};






Pascal's Triangle II

  Total Accepted: 4091  Total Submissions: 13928 My Submissions

Given an index k, return the kth row of the Pascal's triangle.

For example, given k = 3,
Return [1,3,3,1].

Note:
Could you optimize your algorithm to use only O(k) extra space?

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> res(rowIndex + 1, 1);
        for (int m = 1; m <= rowIndex; ++m)
            res[m] = (long long)res[m - 1] * (rowIndex - m + 1) / m;
        return res;
    }
};






Path Sum

  Total Accepted: 5352  Total Submissions: 18062 My Submissions

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

For example:
Given the below binary tree and  sum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool hasPathSum(TreeNode *root, int sum) {
        if (root == NULL) return false;
        if (root->left == NULL && root->right == NULL)
            return (root->val == sum);
        return (hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val));
    }
};






Path Sum II

  Total Accepted: 4708  Total Submissions: 17544 My Submissions

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

For example:
Given the below binary tree and  sum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1

return

[
   [5,4,11,2],
   [5,8,4,5]
]
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    vector<vector<int> > res;
    list<int> lst;
    void dfs(TreeNode *root, int sum) {
        if (root->left == NULL && root->right == NULL) {
            lst.push_back(root->val);
            if (root->val == sum) res.push_back(vector<int>(lst.begin(), lst.end()));
            lst.pop_back();
            return;
        }
        lst.push_back(root->val);
        if (root->left != NULL)
            dfs(root->left, sum - root->val);
        if (root->right != NULL)
            dfs(root->right, sum - root->val);
        lst.pop_back();
    }
public:
    vector<vector<int> > pathSum(TreeNode *root, int sum) {
        if (root != NULL) {
            dfs(root, sum);
        }
        return res;
    }
};







Populating Next Right Pointers in Each Node

  Total Accepted: 9862  Total Submissions: 28977 My Submissions

Given a binary tree

    struct TreeLinkNode {
      TreeLinkNode *left;
      TreeLinkNode *right;
      TreeLinkNode *next;
    }

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

Initially, all next pointers are set to NULL.

Note:

  • You may only use constant extra space.
  • You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).

For example,
Given the following perfect binary tree,

         1
       /  \
      2    3
     / \  / \
    4  5  6  7

After calling your function, the tree should look like:

         1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \  / \
    4->5->6->7 -> NULL
/**
 * Definition for binary tree with next pointer.
 * struct TreeLinkNode {
 *  int val;
 *  TreeLinkNode *left, *right, *next;
 *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 * };
 */
class Solution {
public:
    void connect(TreeLinkNode *root) {
        if (root == NULL) return;
        queue<TreeLinkNode*> q;
        q.push(root);
        int cnt = 1;
        while (!q.empty()) {
            TreeLinkNode *fa = NULL;
            int n = cnt;
            cnt = 0;
            while (n--) {
                TreeLinkNode *p = q.front();
                q.pop();
                if (p->right != NULL) {
                    q.push(p->right);
                    ++cnt;
                }
                if (p->left != NULL) {
                    q.push(p->left);
                    ++cnt;
                }
                p->next = fa;
                fa = p;
            }
        }
    }
};






Populating Next Right Pointers in Each Node II

  Total Accepted: 6907  Total Submissions: 23625 My Submissions

Follow up for problem "Populating Next Right Pointers in Each Node".

What if the given tree could be any binary tree? Would your previous solution still work?

Note:

  • You may only use constant extra space.

For example,
Given the following binary tree,

         1
       /  \
      2    3
     / \    \
    4   5    7

After calling your function, the tree should look like:

         1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \    \
    4-> 5 -> 7 -> NULL
# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#         self.next = None

class Solution:
    # @param root, a tree node
    # @return nothing
    def connect(self, root):
        if root == None:
            return
        queue = [root]
        front = 0
        rear = 1
        cnt = 1
        while front < rear:
            fa = None
            n = cnt
            cnt = 0
            while n > 0:
                n -= 1
                p = queue[front]
                front += 1
                if p.right != None:
                    queue.append(p.right)
                    rear += 1
                    cnt += 1
                if p.left != None:
                    queue.append(p.left)
                    rear += 1
                    cnt += 1
                p.next = fa
                fa = p






Permutations

  Total Accepted: 11511  Total Submissions: 37580 My Submissions

Given a collection of numbers, return all possible permutations.

For example,
[1,2,3] have the following permutations:
[1,2,3][1,3,2][2,1,3][2,3,1][3,1,2], and [3,2,1].

class Solution {
public:
    vector<vector<int> > permute(vector<int> &num) {
        sort(num.begin(), num.end());
        vector<vector<int> > res;
        do {
            res.push_back(num);
        } while (next_permutation(num.begin(), num.end()));
        return res;
    }
};






Permutations II

  Total Accepted: 7819  Total Submissions: 31626 My Submissions

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,
[1,1,2] have the following unique permutations:
[1,1,2][1,2,1], and [2,1,1].

class Solution {
public:
    vector<vector<int> > permuteUnique(vector<int> &num) {
        sort(num.begin(), num.end());
        set<vector<int> > res;
        do {
            res.insert(num);
        } while (next_permutation(num.begin(), num.end()));
        return vector<vector<int> >(res.begin(), res.end());
    }
};









Palindrome Partitioning

  Total Accepted: 8753  Total Submissions: 34272 My Submissions

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

For example, given s = "aab",
Return

  [
    ["aa","b"],
    ["a","a","b"]
  ]
class Solution {
    vector<vector<string>> res;
    vector<string> vec;
    string str;
    int len;
    
    void dfs(const int k) {
        if (k == len) {
            res.push_back(vec);
            return;
        }
        for (int i = k; i < len; ++i) {
            bool palindrome = true;
            for (int p = k, q = i; p < q; ++p, --q) {
                if (str[p] != str[q]) {
                    palindrome = false;
                    break;
                }
            }
            if (palindrome == true) {
                vec.push_back(str.substr(k, i - k + 1));
                dfs(i + 1);
                vec.pop_back();
            }
        }
    }
public:
    vector<vector<string>> partition(string s) {
        str = s;
        len = s.length();
        dfs(0);
        return res;
    }
};









Palindrome Partitioning II

  Total Accepted: 7051  Total Submissions: 40694 My Submissions

Given a string s, partition s such that every substring of the partition is a palindrome.

Return the minimum cuts needed for a palindrome partitioning of s.

For example, given s = "aab",
Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut.

class Solution {
	public:
		int minCut(string s) {
			const int n = s.length();
			vector<vector<bool> > isPalindrome(n, vector<bool>(n, false));
			for (int i = 0; i < n; ++i) isPalindrome[i][i] = true;
			for (int i = 1; i < n; ++i) isPalindrome[i - 1][i] = (s[i - 1] == s[i]);
			for (int len = 3; len <= n; ++len) {
				for (int i = 0, j = i + len - 1; j < n; ++i, ++j)
					isPalindrome[i][j] = (s[i] == s[j] && isPalindrome[i + 1][j - 1]);
			}
			vector<int> dp(n + 1, INT_MAX);
			dp[0] = 0;
			for (int i = 0; s[i]; ++i) {
				for (int j = 0; j <= i; ++j) {
					if (isPalindrome[j][i])
						dp[i + 1] = min(dp[j] + 1, dp[i + 1]);
				}
			}
			return dp[n] - 1;
		}
};

// Precomputation: isPalindrome[N][N] in O(N^2)










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值