50. Pow(x, n) (中等)
double myPow(double x, int n) { double ans = 1; unsigned long long p; if (n < 0) { p = -n; x = 1 / x; } else { p = n; } while (p) { if (p & 1) ans *= x; x *= x; p >>= 1; } return ans; }
96. Unique Binary Search Trees(很快)
1 class Solution { 2 public: 3 int numTrees(int n) { 4 long ans=1; 5 for(int i=n+1;i<=2*n;i++) 6 ans = i*ans/(i-n); 7 return ans/(n+1); 8 } 9 };
94. Binary Tree Inorder Traversal(很快)
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<int> inorderTraversal(TreeNode* root) { 13 stack<TreeNode*> s; 14 vector<int> res; 15 if(root==NULL) return res; 16 TreeNode* p=root; 17 while(!s.empty()||p){ 18 if(p){ 19 s.push(p); 20 p=p->left; 21 } 22 else{ 23 p=s.top(); 24 s.pop(); 25 res.push_back(p->val); 26 p=p->right; 27 } 28 } 29 return res; 30 } 31 };
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<int> res; 13 vector<int> inorderTraversal(TreeNode* root) { 14 if(!root) return res; 15 inorderTraversal(root->left); 16 res.push_back(root->val); 17 inorderTraversal(root->right); 18 return res; 19 } 20 };
1 class Solution { 2 public: 3 vector<int> grayCode(int n) { 4 int len = 1 << n; 5 vector<int> res(len,0); 6 for(int i = 0;i != len;++i){ 7 res[i] =i ^ (i >> 1); 8 } 9 return res; 10 } 11 };